Symlink – How to Find All Symbolic Links in a Directory

symlink

On this question or on this one (for example) you will get solutions on how to look for symlinks pointing to a given directory (let's call it /dir1), while I am interested to symbolic links possibly pointing to any file/folder inside /dir1.

I want to delete such directory but I am not sure that I am safe to do so, as on an other directory (let's call it /dir2), I may have symlinks pointing to inner parts of /dir1.

Further, I may have created these symlinks using absolute or relative paths.
My only help is that I know the symlinks I want to check are on a mounted filesystem, on /dir2.

Best Answer

You can find all the symbolic links using:

find / -type l 

you might want to run this as root in order to get to every place on the disc.

You can expand these using readlink -f to get the full path of the link and you should be able to grep the output against the target directory that you are considering for deletion:

find / -type l -exec readlink -f {} + | grep -F /dir2

Using find / -type l -printf '%l\n' doesn't work as you get relative links like ../tmp/xyz which might be pointing to your target dir, but are not matched because they are not fully expanded.

Related Question