I want to test whether a file is a link to another link. I tried readlink but it doesn't work the way I need it:
ralph@bash4.4.12,1:~/subdir1 $ ll
lrwxrwxrwx 1 pi pi 13 Apr 10 14:34 hellolink -> subdir2/hello
lrwxrwxrwx 1 pi pi 9 Apr 10 14:34 hellolink2 -> hellolink
drwxr-xr-x 2 pi pi 4096 Apr 10 14:33 subdir2
Using readlink I now get either the canonicalized form of the ultimate target or the naked filename of the next link (hellolink):
ralph@bash4.4.12,1:~/subdir1 $ readlink -f hellolink2
/home/ralph/subdir1/subdir2/hello
ralph@bash4.4.12,1:~/subdir1 $ readlink hellolink2
hellolink
But what I need is the full path to the file that hellolink2 points at:
/home/ralph/subdir1/hellolink
Right now I'm doing something like this:
if [ -h "$(dirname hellolink2)/$(readlink hellolink2)" ] ; then
echo hellolink2 is a link
fi
That looks like a lot of overhead when I do it many times in a loop, using find to feed it the filenames.
Is there an easier way?
Best Answer
Use test -L (without readlink) to see if a file is a symbolic link.
Use realpath to get the absolute path of a symlink to a directory.