get absolute path of running script

Using $0 or basename in a script works well if you are calling it using it’s absolute path or if it’s in $PATH. The test script shows how basename and $0 are displayed. Calling the test script from within /usr/local/sbin, does not give any absolute path.

# pwd
/usr/local/sbin
#
# cat test.sh
#!/bin/bash
echo $0
echo `basename $0`
#
#
#
# test.sh 
/usr/local/sbin/test.sh
test.sh
#
# ./test.sh
./test.sh
test.sh
#
#echo 'echo $(readlink -f $0)' >> test.sh
#
# ./test.sh 
./test.sh
test.sh
/usr/local/sbin/test.sh

readlink gives us the full path to the script, no matter how it’s called.