Skip to content

Instantly share code, notes, and snippets.

@rdonkin
Created May 18, 2019 06:55
Show Gist options
  • Save rdonkin/05915bd86475389a94953997f80db9ff to your computer and use it in GitHub Desktop.
Save rdonkin/05915bd86475389a94953997f80db9ff to your computer and use it in GitHub Desktop.
Getting the full path to current script in bash
#!/bin/bash
# All these options work on bash 3.2 on macOS where 'readlink -f' is not available
# Ref http://stackoverflow.com/a/246128
# 1. Get script path, don't canonicalise symlinks used in script path
# ${BASH_SOURCE[0]} is set but includes './' prefix
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" 2>/dev/null)" && pwd 2>/dev/null)"
SCRIPT_PATH=$DIR/$(basename $0)
echo $DIR
echo $SCRIPT_PATH
exit 0
# 2. Canonicalise symlinks - option 1
SCRIPT_PATH="${BASH_SOURCE[0]}";
if ([ -h "${SCRIPT_PATH}" ]) then
while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
echo $SCRIPT_PATH
popd > /dev/null
exit 0
# 3. Canonicalise symlinks - option 2
SOURCE="${BASH_SOURCE[0]}"
# SOURCE="$0"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
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
echo $SOURCE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment