Get directory of Bash script

Most shells (including Bash) don’t have a straightforward way to get the directory of the script being executed. Here’s a common one-liner to get the script directory:

sdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

However, for some HPC batch systems, the above may not work as it copies this script to a temporary directory. This fallback put after the line above works if “qsub” batch command was run from this script’s directory–supposing a script file “gcc.sh” also exists in the same directory as the original script.

[[ ! -f ${sdir}/gcc.sh ]] && sdir=$PWD