I’ve been using this technique for getting the absolute physical path of the running shell script after reading about it somewhere (I don’t remember where).
cd $(dirname "$0") && ABSPATH=$(pwd) && cd - > /dev/null
It seems like it should work perfectly regardless of whether the script is called from an absolute or relative path, i.e. script.sh, ./script.sh, ../script.sh, ../../../lib/script.sh, /Users/../scripts/script.sh, from within another script, etc.
In fact this technique seems like it’s a pretty solid pattern for absolutifying any relative path.
I know a lot of the techniques for doing this tend to not work on one system or another, for one reason or another. So, are there any compatibility problems with this technique? Should it work with pretty much any Unix OS and shell out there, or are there some potential issues?
One potential issue is that it won’t follow symlinks (that is, if
"$0"is actually a symlink to the script, you’ll get the directory containing the symlink, not the actual directory containing the script).Another is that you can’t necessarily trust
"$0". eg If your script is loaded by one of theexecfunctions, it’s trivial to pass in an arbitrary string forargv[0]. I use"$BASH_SOURCE"instead, though that’s obviously bash-specific.You’re missing “s around
$(dirname "$0"), so it won’t work if the directory name eg contains spaces.I believe this fixes these issues: