I have a Bash script that needs to know its full path. I'm trying to find a broadly-compatible way of doing that without ending up with relative or funky-looking paths. I only need to support Bash, not sh, csh, etc.
What I've found so far:
The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via
dirname $0, which is fine, but that may return a relative path (like.), which is a problem if you want to change directories in the script and have the path still point to the script's directory. Still,dirnamewill be part of the puzzle.The accepted answer to Bash script absolute path with OS X (OS X specific, but the answer works regardless) gives a function that will test to see if
$0looks relative and if so will pre-pend$PWDto it. But the result can still have relative bits in it (although overall it's absolute) — for instance, if the script istin the directory/usr/binand you're in/usrand you typebin/../bin/tto run it (yes, that's convoluted), you end up with/usr/bin/../binas the script's directory path. Which works, but...The
readlinksolution on this page, which looks like this:# Absolute path to this script. /home/user/bin/foo.sh SCRIPT=$(readlink -f $0) # Absolute path this script is in. /home/user/bin SCRIPTPATH=`dirname $SCRIPT`