remove broken symlinks in linux

How to Find & Delete Broken Symlinks in Linux

Symlinks are like shortcuts to file & folder locations in Linux. But when you delete the target file/folder of a symlink it gets broken and points to nothing. So every now and then you may need to find & delete broken symlinks in Linux. In this article, we will look at how to search & remove broken symlinks in Linux.

How to Find & Delete Broken Symlinks in Linux

We will use find function to find & remove symlinks in Linux.

Here is the command to find and delete all broken symlinks in your current folder

$ sudo find . -xtype l -delete

Let us look at the above command. find . searches in current folder. -xtype l will look for broken links. It is the opposite of -type l which is used to find active symlinks. -delete deletes all discovered broken links.

If you need to delete all symlinks on your system, replace find . with find /

$ sudo find / -xtype l -delete

Please be careful with the above command will make find recursively search all folders on your system. This can be time-consuming and resource intensive.

Shell Script to Remove Broken Links

You can also create a shell script to find & remove broken symlinks as shown below.

Create empty shell script

$ sudo

Add the following shell script


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

Save and close the file. In the above code, we accept folder location as command line argument and reference it as $1 in our shell script while running find command.

Make the shell script executable.

$ sudo chmod +x

Test your script against different folders

$ sudo ./ /home/data
broken symlinks deleted

If you want to automate the above task, you may also create a cronjob for it. Open crontab

$ sudo crontab -e

Add the following line to run the above shell script every day at 10.a.m. Modify it according to your requirement.

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

Save and close the file. Please make sure to use the full path to your shell script above, instead of using only filename or relative path.

That’s it. As you can see, it is very easy to search and remove broken symlinks in Linux.

Also read:

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

Leave a Reply

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