Bash tip: Absolute path of script

After reading a lot of nonsense (people do not put “quotes” around their stuff, making it not safe for paths including spaces, or they use the non-portable ‘readlink -f’ command which doesn’t work on Mac OS X), this is the real and tested solution for getting the absolute path of the running Bash script:

#!/bin/bash
scriptpath="${BASH_SOURCE[0]}"
scriptdir="$(cd "$(dirname "${scriptpath}")" ; pwd)"
echo "Script path: ${scriptdir}/$(basename "${scriptpath}")" 

And yes, quotes not only can, but have to be nested.

Note that this works even if you source the script.