Different ways for a Bash script to get the directory it's in. Some work better than others.
To set up the demo environment:
mkdir -p ~/tmp/dir_demo cd ~/tmp ln -s dir_demo/ alt_dir_demo cd alt_dir_demo # save the following script as dir_demo.sh ln -s dir_demo.sh alt_demo.sh . alt_demo.sh
# $0 only works if this script is invoked directly as an executable, # not sourced with `. dir_demo.sh` echo "\$0='$0'" # BASH_SOURCE is an array, but it only seems to have one element echo "BASH_SOURCE='$BASH_SOURCE'" echo "BASH_SOURCE[0]='${BASH_SOURCE[0]}'" # Symlinked directories will be preserved DIR_CD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "DIR_CD='$DIR_CD'" # Resolves symlinks to canonical path DIR_READLINK=$(dirname "`readlink -f "${BASH_SOURCE[0]}"`") echo "DIR_READLINK='$DIR_READLINK'" # Resolves script to canonical path and name READLINK_PATH=`readlink -f "${BASH_SOURCE[0]}"` echo "READLINK_PATH='$READLINK_PATH'"
No comments:
Post a Comment