Skip to content

Instantly share code, notes, and snippets.

@olragon
Created October 27, 2022 09:48
Show Gist options
  • Save olragon/f008ff7f418e920014f2d7b42ab2e3a9 to your computer and use it in GitHub Desktop.
Save olragon/f008ff7f418e920014f2d7b42ab2e3a9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# 1. Use bash. Using zsh or fish or any other, will make it hard for others to understand / collaborate. Among all shells, bash strikes a good balance between portability and DX.
# 2. Just make the first line be #!/usr/bin/env bash, even if you don’t give executable permission to the script file.
# 3. Use the .sh (or .bash) extension for your file. It may be fancy to not have an extension for your script, but unless your case explicitly depends on it, you’re probably just trying to do clever stuff. Clever stuff are hard to understand.
# 4. When a command fails, bash exits instead of continuing with the rest of the script.
set -o errexit
# 5. This will make the script fail, when accessing an unset variable.
set -o nounset
# 6. This will ensure that a pipeline command is treated as failed, even if one command in the pipeline fails.
set -o pipefail
# 7. debug with TRACE=1 ./script.sh
if [[ -n "${TRACE-}" ]]; then set -o xtrace; fi
# 8. Use [[ ]] for conditions in if / while statements, instead of [ ] or test.
# 9. Always quote variable accesses with double-quotes.
# 10. Use local variables in functions
# 11. Accept multiple ways that users can ask for help and respond in kind.
# Check if the first arg is -h or --help or help or just h or even -help, and in all these cases, print help text and exit.
# 12. When printing error messages, please redirect to stderr.
# Use echo 'Something unexpected happened' >&2 for this.
# 13. Use long options, where possible (like --silent instead of -s). These serve to document your commands explicitly.
# 14. If appropriate, change to the script’s directory close to the start of the script.
# And it’s usually always appropriate.
# Use cd "$(dirname "$0")", which works in most cases.
# 15. Use shellcheck. Heed its warnings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment