How a sh script finds it's own place
If a shell scripts has to refer other files who's place is only known relative to the script, and the script does not want to rely on the current directory of the shell process calling it, it has to know where it stands in absolute terms.
Newer bash releases provide some special environment variables, but we do not want to rely on them.
This snippets shows how to do this more or less savely and reliable, see below for details
#!/bin/sh MYSELF=$( which $0 ) echo "Myself (can be relative): $MYSELF" MYDIR=$( dirname $( which $0 ) ) echo "My dir (can be relative): $MYDIR" MYSELFCAN=$( readlink -f $( which $0 ) ) echo "Myself canonical = $MYSELFCAN" MYDIRCAN=$( dirname $( readlink -f $( which $0 ) ) ) echo "My dir canonical: $MYDIRCAN" MYSELFSHORT=$( basename $0 ) echo "Myself short: $MYSHORT"
Considering this script is called test.sh and lies in a myscripts/ directory, this solution ...
- works when being called relatively, i.e. scripts/test.sh
- works when being called absolutely i.e. $(pwd)/scripts/test.sh
- works when being called through the path, i.e. ( PATH=$PATH:$(pwd)/myscripts ; test.sh )
- Does NOT WORK when beeing source'd in any way, i.e. . scripts/test.sh!
From: IBCL BLog.
Originally posted: 2009-10-31