Get the absolute path of the current script's working directory

cwd=$(cd "$(dirname "$0")" && pwd)

January 22, 2018dhsrocha

Explanation

dirname path strips the last component from a path, printing the directory part, for example for path/to/example it would print path/to.

$0 is the path of the currently executing script.

By running dirname "$0" we get path to the directory of the currently executing script. This can be a relative path, and we're looking for the absolute path.

To get the absolute path of the script, we cd into the script's directory, and use the pwd command, because it prints the absolute path of the current directory.

Notice the double-quotes around $0 and also $(dirname ...). Without this recommended precaution the script would not work correctly. For example when the directory path contains spaces, the shell would split it to multiple parameters.

Another precaution we applied is chaining the cd and pwd commands with &&, so that we execute pwd if cd was successful, otherwise we could be in the wrong directory and produce incorrect output.