4 ms·
Should use $BASH_SOURCE in place of $0 so it works in files that are sourced. The incantation at the top of all my scripts, that I learned from other HN folks,
by netcoyote 3y ago
Should use $BASH_SOURCE in place of $0 so it works in files that are sourced.
The incantation at the top of all my scripts, that I learned from other HN folks, is:
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
And I guess throw a realpath in there too for symlinks, per TFA.
- js2 3y agoYou don't need realpath. The `cd` into the directory + `pwd` is equivalent. BASH_SOURCE[0] obviously only works with bash.
- account42 3y ago> You don't need realpath Yes you do (or a suitable alternative, e.g. GNU readlink). > The `cd` into the directory + `pwd` is equivalent. You won't know which directory to cd to without realpath. Just stripping off the filename does not get you the correct directory if the file itself is a symlink, which is a common use case.
- js2 3y agoDoh, you're right. Thank you for the correction.
- arp242 3y ago/bin/sh on FreeBSD isn't bash.
- peebeebee 3y agoOn MacOS, we had interoperability uses between different versions somehow, and some of us could not use `realpath` . The following worked for everyone: SCRIPT_DIR=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")").