Bash: how to get the real path to a symbolic link?

Is it possible by executing a file symbolically linked in / usr / local / bin to get the absolute path to the original script? Well, I know where the original file is, and I know this because I link it. But ... I want this script to work, even if I move the source code (and the symlink).

#!/bin/bash
echo "my path is ..."
+6
source share
3 answers

readlinknot a standard command, but it is distributed on Linux and BSD, including OS X, and this is the easiest answer to your question. The BSD and GNU readlink implementations are different, so read the documentation for the one you have.

readlink - script, :

,

cd -P "$symlinkdir"

,

echo "I am in $(cd -P "$symlinkdir" && pwd)"

. , cd -P , , , .

, , . . , , test -L.

+15

, :

$ 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

GNU coreutils - :

$ realpath symlink
/home/test/realscript.sh

. :

realpath realscript.sh
/home/test/realscript.sh

- dirname

$ dirname /home/test/realscript.sh
/home/test

,

echo  $( dirname $(realpath "symlink") )

real script home dir:

script_home=$( dirname $(realpath "$0") )
echo Original script home: $script_home

, /home/test2/, / :

/$ /home/test2/symlink
/home/test
Original script home: /home/test
Original script is: /home/test/realscript.sh
Called script is: /home/test2/symlink

, :)

+1

Linux readlink -f $LINK Mac, greadlink -f $LINK

0

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


All Articles