If I have a specific file in a UNIX filesystem, is there a way to use bash to find all links to that file, both symbolic and hard? If I need different commands for each, what are they?
2 Answers
Try this with GNU find
:
find /start/dir -L -samefile /file/to/check -exec ls -li {} \;
Example output:
1234704 -rw-r--r-- 2 user1 user1 1134 2009-09-11 11:12 ./x1
1234704 -rw-r--r-- 2 user1 user1 1134 2009-09-11 11:12 ./x2
1234983 lrwxrwxrwx 1 user1 user1 2 2009-10-31 16:56 ./testx -> x1
2345059 lrwxrwxrwx 1 user2 user2 2 2010-01-03 16:17 ./x3 -> x1
You could use -ls
instead of -exec
but it will show the inode and other information of the target file instead of the individual files.
-
This output is showing hard and sym links? Sym links indicated by -> arrow?– aaaidanMar 16, 2010 at 2:13
-
@aaaidan: Yes, that's correct. The inode number of x1 and x2 are the same indicating that they are hard links. The arrow indicates a symlink. Using
-L
and-samefile
causes both to be listed. If you omit-L
then symbolic links are not followed (seeman find
). Mar 16, 2010 at 2:45
If you don't have GNU Find you can do this:
find / -inum "$(ls -i /file/to/check | cut -d ' ' -f 1)"
But it won't work for symbolic links.
-
1Oh I see now that this question already answers this: superuser.com/questions/12972/to-see-hardlinks-by-ls Jun 7, 2010 at 13:16