bash get directory for script

First, some warnings from the BashFAQ:

  • Your script does not actually have a location! Wherever the bytes end up coming from, there is no “one canonical path” for it. Never.

  • $0 is NOT the answer to your problem. If you think it is, you can either stop reading and write more bugs, or you can accept this and read on.

The BashFAQ also describes BASH_SOURCE and the applicable caveats.  Here’s some workable, albeit fallible, code from http://stackoverflow.com/questions/59895/can-a-bash-script-tell-which-directory-it-is-stored-in:

# find directory where script may reside
SOURCE="${BASH_SOURCE[0]}"
# resolve $SOURCE till not a symlink
while [ -h "$SOURCE" ]; do 
  DIR="$( cd -P "$(dirname "$SOURCE")" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$(cd -P "$(dirname "$SOURCE")" && pwd && \
  echo x)"
DIR="${DIR%x}"
echo Script $0 resides in directory $DIR