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")" |
Author
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$0or$BASH_SOURCEdon't automatically resolve symlinksreadlink -F(or ‘follow’) is unavailable on some *NIXes, notably OS X; so I duplicate its' functionality with a while-loop$0is 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_SOURCEarray (which is supported by bothzshandbash). Using$0instead if POSIX compatibility /dashis more important to you than situations where the program-name won't be the path.