The Tools to Fix Broken Symlinks
There’s an incredibly helpful application called simply symlinks in most repositories. It’s a simple command-line utility that will give helpful output and options for deleting those same broken symlinks. To install it, use the following commands: There are a couple of key options for symlinks. Those are -d, which will delete dangling links, and -r, which will recursively do whatever option you specify through subdirectories. You can also use the built-in find tool in Linux. This is a less user-friendly example, but it’s helpful to learn the find command and how it works.
Breaking Symlinks
First, I’ll create a symbolic link. This involves taking an existing file and using the ln command to link it to a file that doesn’t exist yet. That would be like the following example for me. You can see via the ls command that the link exists. Now, I’ll break that symlink. You can see that even though I’ve removed the original file, the ls -l command still reports the link. This is where the problem comes in. These files might be in different directories, which makes it much harder to check if the original file is still there.
Finding and Fixing Broken Symlinks
The way to fix broken symlinks is to just delete them. It’s impossible to bring them back, so you just have to clear them from the virtual directory tree. To report broken symlinks with the symlinks tool, use the following command: Note the “.” indicating the present working directory. Change this for whichever directory you’re trying to search. The output may look like this: Indicating that “linked-file.txt” is dangling and that the symlink is broken. To delete them, use the following command: The output will look similar to last time but will also include a line for “deleted.” To fix broken symlinks with find, use the following command: Note once again that the “.” representing the present working directory. This will produce a less user-friendly output but will still be helpful. And to delete, add the delete option. You won’t get any output for this one, but if you run it again without the -delete option, you won’t find anything. That’s it. Now you can easily find broken symlinks and delete them before they cause more issues. There are more tutorials on symlinks that you should check out. You can also learn more about the difference between a symlink and a hard link and when you should use them.