Tips & Tricks Tips & Tricks How to retrieve the path where the running script is located?

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).

Share the love!

Liked this article? Please consider sharing it on your favorite network, it really helps me a lot!

You can also add your valuable insights by commenting below.