When writing a bash script, how do I get the absolute path of the location of the current file?

You can get the full path like:

realpath "$0"

And as pointed out by Serg you can use dirname to strip the filename like this

dirname "$(realpath $0)"

or even better to prevent awkward quoting and word-splitting with difficult filenames:

temp=$( realpath "$0"  ) && dirname "$temp"

Much better than my earlier idea which was to parse it (I knew there would be a better way!)

realpath "$0" | sed 's|\(.*\)/.*|\1|'

Notes

  • realpath returns the actual path of a file
  • $0 is this file (the script)
  • s|old|new| replace old with new
  • \(.*\)/ save any characters before / for later
  • \1 the saved part

if the script is in your path you can use something like

$ myloc=$(dirname "$(which foo.sh)")
$ echo "$myloc"
/path/to/foo.sh

EDIT: after reading comments from Serg, this might be a generic solution which works whether the script is in your path or not.

myloc==$(dirname "$(realpath $0)")
dirname "$myloc"

The accepted answer seems perfect. Here's another way to do it:

cd "$(dirname "$0")"
/bin/pwd

/bin/pwd prints the real path of the directory, as opposed to the pwd builtin command.