Find inbound symlinks

In Linux, what is the most effective means to find all symbolic web links that indicate an offered documents (no matter whether the symlink is loved one or outright)? I understand this will certainly call for scanning the entire filesystem.

0
2019-05-18 22:33:46
Source Share
Answers: 2

Perhaps the fastest means would certainly be:

target="/usr/bin/firefox"    # change me
dir="/usr/bin"               # change me
realtarget="$(realpath "$target")"
for file in $(find "$dir" -print); do
    realfile="$(realpath "$file")"
    test "$realfile" = "$realtarget" && echo "$file"
done

But it is not really reliable.

If you do not have realpath, install it, as an example apt-get install realpath. You can additionally make use of stat -N or ls -l or pwd -P to mimic realpath, yet those means are harder.

Additionally, the above instance will not take care of documents names with rooms in it effectively. Below is a far better means to do it. Keep in mind that IFS=$'\n' calls for bash or zsh.

OIFS="$IFS"
IFS=$'\n'
target="/usr/bin/firefox"    # change me
dir="/usr/bin"               # change me
realtarget="$(realpath "$target")"
find "$dir" -print | while read -r file; do
    realfile="$(realpath "$file")"
    test "$realfile" = "$realtarget" && echo "$file"
done
IFS="$OIFS"
0
2019-05-21 08:42:26
Source

GNU find has the -samefile examination. According to the male web page:

-samefile name
    File refers to the same inode as name. When -L is in 
    effect, this can include symbolic links.
$ find -L / -samefile /path/to/file

This will certainly find all web links to /path/to/file, that includes tough web links and also the documents itself. If you just desire symlinks, you can independently examine the outcomes of find (test -L).

You need to check out what the results of -L are and also make certain that it will not create you any kind of troubles with your search.

Keep in mind: While the documents claims it seeks files with the very same inode number, it does show up to function throughout filesystems.

as an example/ residence and also/ tmp are different filesystems

$ touch ~/testfile
$ ln -s ~/testfile /tmp/foo
$ ln -s /tmp/foo /tmp/bar
$ mkdir /tmp/x
$ ln -s ~/testfile /tmp/x/baz
$ find -L /tmp -samefile ~/testfile
/tmp/bar
/tmp/foo
/tmp/x/baz

Note just how this is returning/ tmp/bar, which is a symlink to/ tmp/foo, which is a symlink to ~/ testfile. If you just intended to find straight symlinks to your target documents, this will not function.

0
2019-05-21 06:19:49
Source