Shell Script Best Practices
Shell Script Best Practices Things Just make the first line be #!/usr/bin/env bash. Use the .sh (or .bash) extension for your file. Use set -o errexit at the start of your script. Prefer to use set -o nounset. use "${VARNAME-}" instead of "$VARNAME" Use set -o pipefail. Use set -o xtrace, with a check on $TRACE env variable. if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace; fi People can now enable debug mode, by running your script as TRACE=1 ./script.sh instead of ./script.sh. Use [[ ]] for conditions in if / while statements, instead of [ ] or test. Always quote variable accesses with double-quotes. Use local variables in functions. When printing error messages, please redirect to stderr. Use echo 'Something unexpected happened' >&2 for this. Use long options, where possible (like --silent instead of -s). If appropriate, change to the script’s directory close to the start of the script. Use cd “$(dirname “$0”)”, which works in most cases. Use shellcheck. Heed its warnings. Template #!/usr/bin/env bash set -o errexit set -o nounset set -o pipefail if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace fi if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then echo 'Usage: ./script.sh arg-one arg-two This is an awesome bash script to make your life better. ' exit fi cd "$(dirname "$0")" main() { echo do awesome stuff } main "$@"