Last active
October 28, 2022 20:52
-
-
Save dapithor/f577f4c96927f333ce47738375046fd1 to your computer and use it in GitHub Desktop.
Best practices for bash
This file contains hidden or 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 | |
| # 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