Skip to content

Commit a0112a9

Browse files
committed
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.
1 parent 69cc1c1 commit a0112a9

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

snippets/sh-mode/script-dir

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# -*- mode: snippet -*-
2+
# name: the currently executing/sourced script's directory
3+
# key: script-dir
4+
# --
5+
# See https://stackoverflow.com/a/246128/3561275
6+
SOURCE="\${BASH_SOURCE[0]}"
7+
while [ -h "\$SOURCE" ]; do # resolve \$SOURCE until the file is no longer a symlink
8+
DIR="\$( cd -P "\$( dirname "\$SOURCE" )" >/dev/null 2>&1 && pwd )"
9+
SOURCE="\$(readlink "\$SOURCE")"
10+
[[ \$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
11+
done
12+
DIR="\$( cd -P "\$( dirname "\$SOURCE" )" >/dev/null 2>&1 && pwd )"
13+
14+
$0

0 commit comments

Comments
 (0)