Get directory of running script

In shell scripts, it is often useful to know which directory the script is running from. Here is a way to get this information:

curdir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

“$0” is the script name. “dirname” returns the corresponding directory. “cd” changes to that directory, which becomes the working directory. “pwd” returns it, so it can be assigned to the variable “curdir”. The option “-P” tells to only use the physical directory structure and to not follow symbolic links. Note that “cd” is encapsulated using the “$(…)” syntax, so it does not change the working directory for the rest of the script.