Skip to content

Instantly share code, notes, and snippets.

@dansomething
Last active June 16, 2021 11:44
Show Gist options
  • Save dansomething/811fa008e51214c8b4ec0450405fa26f to your computer and use it in GitHub Desktop.
Save dansomething/811fa008e51214c8b4ec0450405fa26f to your computer and use it in GitHub Desktop.
Determine the path to this Bash script
#!/usr/bin/env bash
set -eou pipefail
# Determine the path to this script...
# Short version
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# Long version (handles symlinks)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment