3 ms·
Your recommendations are a little off in the following ways: You should use /usr/bin/env bash for the shebang. Some distros, such as nixos, don't have /bin/bas
by TheDong 7y ago
Your recommendations are a little off in the following ways:
You should use /usr/bin/env bash for the shebang. Some distros, such as nixos, don't have /bin/bash.
You need more quoting in the dirname line. cd "$(dirname "$0")" is what you need. The outer quotes are in case the directory has a space or special character in it, the inner ones are in case the script does.
That being said, you may also want $BASH_SOURCE rather than $0, but the reasons behind that are complicated. You may also want to support cases where the script is a symlink depending on what you're doing.
- arglebargle123 7y agoUsing 'env bash' to find the local path is definitely the way to go. It also supports that occasional case where the user has installed modern bash somewhere in their local path (under their home directory) and finds that rather than the system copy. #!/usr/bin/env bash If you really want a predictable environment I usually go with something like this after the shebang, it supports bash and not-bash shells: case "$(readlink /proc/$$/exe)" in */bash) set -euo pipefail ;; *) set -eu ;; esac PATH=/usr/sbin:/usr/bin:/sbin:/bin \unalias -a I don't usually cd anywhere unless I need to.