Get path of bash script
31 Aug 2022Example depth-indented listing of files
/
|-/tmp
| |-foo
| | |-bin
| | | |-script.sh
|-/home
| |-mike
| | |-bin
| | | |-script_link -> (symlink to /tmp/foo/bin/script.sh)
Script 1
#!/usr/bin/env bash
# content of /tmp/foo/bin/script.sh
BASE_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
echo $BASH_PATH
Get script path by execute /tmp/foo/bin/script.sh
$ /tmp/foo/bin/script.sh
/tmp/foo/bin # script directoery
$ /home/mike/bin/script_link
/home/mike/bin # link directory
Script 2
Get path of current script when executed through a symlink
#!/usr/bin/env bash
# content of /tmp/foo/bin/script.sh
BASE_PATH="$(dirname "$(readlink "$0")")"
echo $BASH_PATH
$ /tmp/foo/bin/script.sh
. # current directory
$ /home/mike/bin/script_link
/tmp/foo/bin # script directory
Script 3
What about if get path of script when wexecuted through a symlink. 1
#!/usr/bin/env bash
# content of /tmp/foo/bin/script.sh
BASE_PATH="$( cd "$( dirname $(readlink "${BASH_SOURCE[0]}") )" >/dev/null && pwd )"
echo $BASH_PATH
$ /tmp/foo/bin/script.sh
/tmp/foo/bin # script directory
$ /home/mike/bin/script_link
/tmp/foo/bin # script directory