Last active
August 29, 2015 14:12
-
-
Save ELLIOTTCABLE/7fac65d478a1ca56ac4c to your computer and use it in GitHub Desktop.
Smarter $0 for shell-scripts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Instead of ... | |
# | |
# SCRIPT=$0 | |
# SCRIPTDIR=`dirname $0` | |
# | |
# ... use: | |
SCRIPT="$( | |
cd "$(dirname "${BASH_SOURCE[0]}")" | |
SCRIPT="$(basename "${BASH_SOURCE[0]}")" | |
while [ -L "$SCRIPT" ]; do | |
SCRIPT="$(readlink "$SCRIPT")" | |
cd "$(dirname "$SCRIPT")" | |
SCRIPT="$(basename "$SCRIPT")" | |
done | |
PHYS_DIR="$(pwd -P)" | |
echo "$PHYS_DIR/$SCRIPT" | |
)" | |
SCRIPTDIR="$(dirname "$SCRIPT")" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Superior to / combination of other solutions I've been able to find, as:
$(this)
is generally better practice thanthis
$0
or$BASH_SOURCE
don't automatically resolve symlinksreadlink -F
(or ‘follow’) is unavailable on some *NIXes, notably OS X; so I duplicate its' functionality with a while-loop$0
is the name of the executing program, which isn't remotely guaranteed to be the path to the script (or even a path at all), so we use the$BASH_SOURCE
array (which is supported by bothzsh
andbash
). Using$0
instead if POSIX compatibility /dash
is more important to you than situations where the program-name won't be the path.