Interview Prep/Shell Scripting/Variables, quoting and expansions

How do you get the directory a script lives in, reliably?

IntermediateConceptVariables, quoting and expansions
Answer
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# Follow symlinks too (GNU readlink, e.g. /usr/local/bin/tool -> /opt/tool/bin/tool):
SCRIPT_DIR=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")

${BASH_SOURCE[0]} is correct even when the file is sourced, unlike $0. Never rely on the current directory: cron and systemd start in / or $HOME. On macOS, use greadlink from coreutils or realpath.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions