How to find files that symlink to a target file

A great command was shown to me today that I wanted to share.  The problem is that there is not easy way to reverse lookup on dynamic symlinks.  By default linux based symlinks are simply a one way alias.  The target file in a symlink has no clue that the source file is linking to it.  This prevents you from doing an easy lookup to search based upon who is linking to a specific target file.

However there is a creative workaround.  Let’s assume you have a file named “/foo/bar” and various symlinks pointing to that file.  This will allow you to in essence find all of the files that contain this symlink reference.  A way to search based upon symlink targets.

find / -ls | grep — ‘->’ | grep ‘/foo/bar’

There is really no rocket science here.  Let’s look at how this is able to find the symlink reference targets

First and for most this is just a simple find command.  for the sake of this demo we are finding across the root of the server.  In most environments that sort of search for symlinks would take a long time, so feel free to change that as appropriate.

Option “-ls” is a standard display option.

We then pipe the output and grep for the “->” symbol which is found in symlinks.  We then perform another grep on the file name itself that we are looking for.  The return result the looks something like this:

[ben@testBox ~]# find ./ -ls | grep — ‘->’ | grep ‘/foo/bar/’

725872    0 lrwxrwxrwx   1 ben     users           49 Jan 11 16:23 ./current -> /foo/bar/
725872    0 lrwxrwxrwx   1 ben     users           49 Jan 11 16:22 ./test2 -> /foo/bar/
725872    0 lrwxrwxrwx   1 ben     users           49 Jan 11 16:21 ./test1 -> /foo/bar/

 

So – considering that there is no built in solution for finding who is referencing a symlink – I really liked this as a quick and easy workaround to find all files that are pointing to a specific symlink location.

Comments

comments

Posted in and tagged , .