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

Want to work together? Get in touch.

Related

Keyboard shortcuts

/Open search
CtrlKOpen search (Cmd+K on macOS)
?Show this cheat sheet
Ctrl/Show this cheat sheet (Cmd+/ on macOS)
EscClose search or this cheat sheet

Turns off the single-key shortcuts (/, ?). Ctrl/Cmd+K and Ctrl/Cmd+/ stay.