Skip to content

Instantly share code, notes, and snippets.

@dapithor
Last active October 28, 2022 20:52
Show Gist options
  • Select an option

  • Save dapithor/f577f4c96927f333ce47738375046fd1 to your computer and use it in GitHub Desktop.

Select an option

Save dapithor/f577f4c96927f333ce47738375046fd1 to your computer and use it in GitHub Desktop.
Best practices for bash
#!/usr/bin/env bash
# https://github.com/ralish/bash-script-template
#{{{ Bash settings
# shorthand: set -euo pipefail ...
# Only enable these shell behaviours if we're not being sourced
# Approach via: https://stackoverflow.com/a/28776166/8787985
if ! (return 0 2> /dev/null); then
# A better class of script...
set -o errexit # Exit on most errors (see the manual)
set -o nounset # Disallow expansion of unset variables
set -o pipefail # Use last non-zero exit code in a pipeline
fi
# Enable errtrace or the error trap handler will not work as expected
set -o errtrace # Ensure the error trap handler is inherited
#}}}
#{{{ Variables
IFS=$'\t\n' # Split on newlines and tabs (but not on spaces)
script_name=$(basename "${0}")
script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
readonly script_name script_dir
#}}}
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
# Enable xtrace if the DEBUG environment variable is set
#if [[ ${DEBUG-} =~ ^1|yes|true$ ]]; then
# set -o xtrace # Trace the execution of the script (debug)
#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")"
# Helper functions
cleanup() {
result=$?
# Your cleanup code here
exit ${result}
}
trap cleanup EXIT ERR
main() {
echo do awesome stuff
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment