Created
November 24, 2022 22:30
-
-
Save cristaloleg/bb5b19f205ef6440b57d044e09f1cf88 to your computer and use it in GitHub Desktop.
Bash best practices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -Eeuxo pipefail | |
set -o errexit | |
set -o nounset | |
set -o pipefail | |
trap "echo ERR trap fired!" ERR | |
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 "$@" | |
# When you want to access a variable that may or may not have been set, use "${VARNAME-}" instead of "$VARNAME", and you’re good. | |
# Sources: | |
# https://sharats.me/posts/shell-script-best-practices/ | |
# https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/ | |
# https://betterdev.blog/minimal-safe-bash-script-template/ | |
# https://ashishb.net/all/the-first-two-statements-of-your-bash-script-should-be/ | |
# https://dev.to/bobbyiliev/the-only-bash-scripting-cheat-sheet-that-you-will-ever-need-55c7 | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment