how to find & delete broken symlinks in linux

How to Find & Delete Broken Symlinks in Linux

Symlinks, known as symbolic links, are the shortcuts to files and directories in Linux. When a file/directory which has a symlink pointing to it is deleted, then the symlink points to nothing. Such symlinks are also known as dangling symlinks or broken symlinks. So in this case, you will need to find and delete broken symlinks otherwise, they will return errors when you refer to them. In this article, we will learn how to find & delete broken symlinks in Linux.

How to Find & Delete Broken Symlinks in Linux

You can use find function to easily find and delete broken symlinks. Here is a sample command to find broken symlinks in Linux.

$ find . -xtype l -delete

In the above command, we use ‘-xtype l’ option to look for broken links. The find command searches in current directory represented by dot(.). If you want to find active symlinks use ‘-type l’ option. -delete deletes all symlinks that are broken and discovered.

If you want to find an delete broken symlinks in a specific directory such as /home/data, replace dot with the directory path.

$ find /home/data -xtype l -delete

The above command is useful for only a single specific directory. If you want to this regularly, then you can also create a shell script to delete symlinks as shown below.

First, we create an empty shell script.

$ vi delete_symlinks.sh

Add following shell scripts.

!#/bin/bash

sudo find $1 -xtype l -delete
echo "broken symlinks deleted"

In the above code, we accept the directory location as command line argument, stored in $1. Save and close the file. Make shell script executable using chmod command. chmod command is used to modify file/directory permissions.

$ sudo chmod +x delete_symlinks.sh

You can test your script against different directories as shown below.

$ ./delete_symlinks.sh /home/data
broken symlinks deleted

You can also automate the above tasks by adding to a crontab.

$ crontab -e

Add the following line to run the shell script every day at 10.a.m.

0 10 * * * sudo nohup /home/delete_symlink.sh & >/dev/null 2>&1

Save and close the file. Make sure to provide full file path in crontab.

In this article, we have learnt how to easily search and remove broken symlinks.

Also read:

How to Remove Duplicates from Python List
How to Get Key from Value in Python Dictionary
How to Flatten List of Lists in Python
How to Find Item in Python List
How to Parse CSV File in Shell

Leave a Reply

Your email address will not be published. Required fields are marked *