A bash snippet to get the directory a script is located in

See https://stackoverflow.com/a/246128/3561275 for details about how
this works.
This commit is contained in:
Omair Majid 2019-05-10 16:04:41 -04:00
parent 69cc1c19c7
commit a0112a9ee6
1 changed files with 14 additions and 0 deletions

View File

@ -0,0 +1,14 @@
# -*- mode: snippet -*-
# name: the currently executing/sourced script's directory
# key: script-dir
# --
# See https://stackoverflow.com/a/246128/3561275
SOURCE="\${BASH_SOURCE[0]}"
while [ -h "\$SOURCE" ]; do # resolve \$SOURCE until the file is no longer a symlink
DIR="\$( cd -P "\$( dirname "\$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="\$(readlink "\$SOURCE")"
[[ \$SOURCE != /* ]] && SOURCE="\$DIR/\$SOURCE" # if \$SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="\$( cd -P "\$( dirname "\$SOURCE" )" >/dev/null 2>&1 && pwd )"
$0