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.


Wrapper shell script for pipelines

This shell script (also on Github) is a wrapper to run a command on all files from a set of directories, and output to directories with matching names. I often use it in pipelines, to batch process files in a project directory structure similar to the one used by ProjectTemplate.