Things
- Just make the first line be
#!/usr/bin/env bash. - Use the
.sh(or.bash) extension for your file. - Use
set -o errexitat the start of your script. - Prefer to use
set -o nounset.- use
"${VARNAME-}"instead of"$VARNAME"
- use
- Use
set -o pipefail. - Use
set -o xtrace, with a check on$TRACEenv variable.if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace; fi- People can now enable debug mode, by running your script as
TRACE=1 ./script.shinstead of./script.sh.
- Use
[[ ]]for conditions inif/whilestatements, instead of[ ]ortest. - Always quote variable accesses with double-quotes.
- Use
localvariables in functions. - When printing error messages, please redirect to stderr.
- Use
echo 'Something unexpected happened' >&2for this.
- Use
- Use long options, where possible (like
--silentinstead 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 "$@"
