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 delete_symlinks.sh
Add the following shell script
!#/bin/bash 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 delete_symlinks.sh
Test your script against different folders
$ sudo ./delete_symlinks.sh /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/delete_symlink.sh & >/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.