How to compare 2 symbolic links in unix (Linux)?

What would be an elegant way to compare 2 symbolic links on Unix?

Suppose I entered the following commands:

ln -s /usr/share/g s1
ln -s /usr/share/g s2
ln -s ../share/g /usr/lib/s3
ln -s /usr/share/h s4

then I would like to have a team that says s1 and s2 are equal (regardless of whether / usr / share / g really exists), that s1 and s4 are not equal, s2 and s4 are not equal. (For my purpose, it is enough that s3 is reported to be different from s1 and s2, however, if a comparison after normalizing the path can be done, this may be useful for.)

+3
source share
4 answers

For GNU systems (and possibly others, but I can't say), there readlink(1):

$ touch a
$ ln -s a b
$ readlink b
a

You can use this in comparison:

$ test $(readlink -f a) = $(readlink -f b)
$ echo $?
0
+12

stat -L . :

#!/bin/bash
DI_A=$(stat -c "%d.%i" -L "$1")
DI_B=$(stat -c "%d.%i" -L "$2")

if [ "$DI_A" == "$DI_B" ]; then
   echo "same file"
else
   echo "other file"
fi
+3

stat -L, ls -l ( sed ):

fileone=`ls -l s1 | sed 's/.*-> //'`
filetwo=`ls -l s2 | sed 's/.*-> //'`
if [ "$fileone" = "$filetwo" ]
then
    echo "They're the same!"
fi

To normalize the path, use realpath:

fileone=`ls -1 s1 | sed 's/.*-> //'`
fileone=`realpath $fileone`
# etc...
0
source

2 ways that I can think of, you can use ls -l for both files. after "->" you can see the actual path.eg path

# ls -ltr msdfasdffff
lrwxrwxrwx 1 root root 10 Jun 30 19:05 msdfasdffff -> blah.sh

you can get the file name using

# ls -l msdfasdffff  | awk -F"-> " '{print $NF}'
blah.sh

then you can compare it with another link.

another way is to use find

# var1=$(find . -name "s1" -printf "%l")
# var2=$(find . -name "s2" -printf "%l")

then you can compare 2 variables using if / else

-1
source

Source: https://habr.com/ru/post/1712543/


All Articles