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.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate