How to retrieve the path where the running script is located?

By Romain Dorgueil

Short answer

In your script, define the $__PATH__ variable as follow:

__PATH__=$(cd $(dirname "$0"); pwd)

Details

This solution is pretty complicated and expensive (spawns two subshells), but all other attempts I made got tricked by edge cases.

Some traps:

  • You have to avoid . and .. entries that can occur in $0
  • You need to abstract the fact the path can contain symbolic links.
  • You must be as cross-platform as possible (readlink was a candidate to solve this, but for example, OSX and GNU implementations have very different syntaxes).