Commands.page Logo

How to Find Broken Symbolic Links in Ubuntu Directory Tree

Broken symbolic links can clutter your filesystem and cause errors in scripts or applications. This article explains how to identify these invalid links within a specific directory tree on Ubuntu using command-line tools. You will learn the specific commands to locate and optionally remove these broken references to maintain a healthy system.

Using the Find Command

The most effective way to locate broken symbolic links is using the find utility built into Ubuntu. Open your terminal and navigate to the directory you wish to scan. Run the following command to list all symbolic links where the target file no longer exists:

find . -type l ! -exec test -e {} \; -print

In this command, . represents the current directory. You can replace it with any specific path, such as /home/user/documents. The -type l flag tells find to look only for symbolic links. The ! -exec test -e {} \; portion checks if the link target does not exist, and -print outputs the path of the broken link.

Once you have identified the broken links, you can remove them automatically using a similar find command. It is recommended to run the search command first to verify the list before deletion. To delete the broken links safely, use the -delete flag:

find . -type l ! -exec test -e {} \; -delete

This command finds all symbolic links in the current directory tree that point to non-existent files and removes them immediately. Always ensure you have the necessary permissions to delete files in the target directory, using sudo if required for system folders.