Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all symlinks to a file?

This is my hierarchy:

aaaaaaaa
|_q
  |_a.txt
|_w
  |_l1
  |_l2

l1 and l2 are symlinks to a.txt. I run this code to find all symlinks to a.txt in the /aaaaaaaa:

find ~/aaaaaaaa/ -exec ls -a {} ';' | grep '/home/khodor/aaaaaaaa/q/a.txt'

And it obviously doesn't work, cause I must compare realpath of file with path of a.txt. In what way I should do this?

like image 447
dasfex Avatar asked Dec 18 '22 14:12

dasfex


2 Answers

If you have GNU/BSD find just use -samefile primary.

$ find -L ~/aaaaaaaa/ -samefile ~/aaaaaaaa/q/a.txt 
/home/oguz/aaaaaaaa/q/a.txt
/home/oguz/aaaaaaaa/w/l2
/home/oguz/aaaaaaaa/w/l1
like image 138
oguz ismail Avatar answered Dec 31 '22 23:12

oguz ismail


referenceid=$(stat -Lc '%d-%i' /home/khodor/aaaaaaaa/q/a.txt)
find ~/aaaaaaaa/ -type l -print0 | while IFS= read -r -d '' filename
do
  if [ "$(stat -Lc '%d-%i' "$filename")" = "$referenceid" ]
  then
    printf -- '%s\n' "$filename"
  fi
done

This initially gets a unique ID for a base file, e.g. /home/khodor/aaaaaaaa/q/a.txt. The ID is computed from the device ID and the inode, using stat.

Then it parses your folder using file, limited to symbolic links (thanks to -type l), and for each filename it gets the device ID and inode using stat again, using its -L option that dereferences the link before fetching the ID.

For each device ID and inode that matches the reference ID, it prints the filename.

like image 20
vdavid Avatar answered Dec 31 '22 23:12

vdavid