Last active
February 6, 2025 13:02
-
-
Save FMeinicke/902d4504cdaabf81788dd0f081e0538a to your computer and use it in GitHub Desktop.
Bash script template
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
| #!/bin/bash | |
| # | |
| # My bash script template | |
| # | |
| # inspired by the best practises found at | |
| # https://sharats.me/posts/shell-script-best-practices/ and | |
| # https://bertvv.github.io/cheat-sheets/Bash.html | |
| here="${0%/*}" | |
| self="${0##*/}" | |
| # enable trace output if $TRACE env variable is set to a non-zero value | |
| if [[ "${TRACE-0}" == "1" ]]; then | |
| set -o xtrace | |
| fi | |
| # abort on nonzero exitstatus | |
| set -o errexit | |
| # abort on unbound variable | |
| set -o nounset | |
| # don't hide errors within pipes | |
| set -o pipefail | |
| usage() { | |
| echo "Usage: ${0} [ -h | --help ] [--some-opt] SOME_ARGUMENTS | |
| ARGUMENTS | |
| SOME_ARG | |
| description | |
| OPTIONS | |
| -h | --help | |
| Shows this help | |
| --some-opt | |
| description | |
| " | |
| exit 1 | |
| } | |
| some_opt=false | |
| # Parse options with getopt | |
| OPTIONS=$(getopt -o h --long help,some-opt -n "${0}" -- "${@}") | |
| # shellcheck disable=SC2181 | |
| if [[ ${?} != 0 ]]; then | |
| exit 1 | |
| fi | |
| eval set -- "${OPTIONS}" | |
| while true; do | |
| case "${1}" in | |
| -h|--help) | |
| usage | |
| shift | |
| ;; | |
| --some-opt) | |
| some_opt=true | |
| shift | |
| ;; | |
| --) | |
| shift | |
| break | |
| ;; | |
| *) | |
| echo "Invalid option: ${1}" 1>&2 | |
| usage | |
| ;; | |
| esac | |
| done | |
| # Check if correct number of arguments | |
| if [[ ${#} != 1 ]]; then | |
| usage | |
| fi | |
| some_arg=${1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment