Skip to content

Instantly share code, notes, and snippets.

@ELLIOTTCABLE
Last active August 29, 2015 14:12
Show Gist options
  • Save ELLIOTTCABLE/7fac65d478a1ca56ac4c to your computer and use it in GitHub Desktop.
Save ELLIOTTCABLE/7fac65d478a1ca56ac4c to your computer and use it in GitHub Desktop.
Smarter $0 for shell-scripts.
# 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")"
@ELLIOTTCABLE
Copy link
Author

Superior to / combination of other solutions I've been able to find, as:

  • $(this) is generally better practice than this
  • quoting, quoting e'erywhere!
  • $0 or $BASH_SOURCE don't automatically resolve symlinks
  • readlink -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 both zsh and bash). Using $0 instead if POSIX compatibility / dash is more important to you than situations where the program-name won't be the path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment