0

I want to obtain the path of a Bash script, is when it’s executed through a symlink.

In this case, $0 is -bash, while BASH_SOURCE is the symlink’s path.

Can I obtain the script’s path through some shell variable, built-in shell command, or external command?

Will BASH_SOURCE always holds the initial symlink’s path, even if the script is executed through several levels of indirection (multiple symlinks)?

Could I use ls with BASH_SOURCE to always retrieve the script’s path?

Shuzheng
  • 4,411

1 Answers1

4

realpath or readlink -f from GNU coreutils might help:

$ ls -l foo.sh bar.sh whereami.sh
lrwxrwxrwx 1 ilkkachu ilkkachu  6 Jul 31 19:01 bar.sh -> foo.sh*
lrwxrwxrwx 1 ilkkachu ilkkachu 11 Jul 31 19:01 foo.sh -> whereami.sh*
-rwxr-xr-x 1 ilkkachu ilkkachu 36 Jul 31 19:02 whereami.sh*
$ cat whereami.sh
#!/bin/bash
echo "$BASH_SOURCE"
realpath "$BASH_SOURCE"
$ ./bar.sh
./bar.sh
/tmp/whereami.sh
ilkkachu
  • 138,973