Get directory of Bash script

Most shells don’t have a straightforward way to get the directory of the script being executed. There are one-line commands to get the script directory in each shell:

Shell one-line command
Bash sdir=$(dirname $(realpath ${BASH_SOURCE[0]}))
Zsh sdir=${${(%):-%x}:A:h}

Execution of scripts without a shebang goes to the system “/bin/sh”, which may be in POSIX mode and so may not support Bash- or Zsh-specific features.

With HPC batch systems, the above likely does not work as intended since the HPC batch scheduler generally copies the batch script to a temporary directory. Each HPC batch system has a way of indicating from where the batch script was originally submitted - which can be distinct from the script’s original directory. The technique is to be mindful of what directory one is submitting the HPC batch job from.

Batch system environment variable indicating submission directory
Slurm SLURM_SUBMIT_DIR
PBS PBS_O_WORKDIR
LSF LS_SUBCWD

Using “~” or “$HOME” within the batch script may not point to the user home directory due to the possibility of LSF account mapping, a different automount prefix, or a container environment. The HPC generally has a networked drive available with environment variables pointing to the intended directories for data and working storage. Use the documentation for the intended HPC batch system to determine the appropriate environment variables for data, scratch, and working directories. These environment variables would be used inside the HPC batch script.