lets assume we have real script or file and symbolic link to it:
$ ls -la
-rwxr-xr-x 1 root root 0 Mar 20 07:05 realscript.sh
lrwxrwxrwx 1 root root 10 Mar 20 07:05 symlink -> realscript.sh
And the part of GNU coreutils are few very useful commands:
$ realpath symlink
/home/test/realscript.sh
see also on original:
realpath realscript.sh
/home/test/realscript.sh
Also very good combination in scripting is to use dirname
on script
$ dirname /home/test/realscript.sh
/home/test
so to wrap it up, you can use in script
echo $( dirname $(realpath "symlink") )
or to get and store in variable real script home dir and save code to get real path script realscript.sh:
script_home=$( dirname $(realpath "$0") )
echo Original script home: $script_home
Where "$0" is defined as "self" in shell script.
To test everything, we put symlink into /home/test2/, amend some additional things and run/call it from root directory:
$ /home/test2/symlink
/home/test
Original script home: /home/test
Original script is: /home/test/realscript.sh
Called script is: /home/test2/symlink
Please try to write your self the amended outputs :)
Update 2021, there is also command:
readlink - print resolved symbolic links or canonical file names
DESCRIPTION
Note realpath(1) is the preferred command to use for canonicalization functionality.
readlink -f filename
gives you a full path to link target. – Origenreadlink
, not for BSD. – Demographystat
is more consistently available, but it too has different usage depending on your operating system. – Modelingrealpath
,chase
andreadlink
. No doubt other platforms have a wide choice, too. – Ruination