Skip to content

Instantly share code, notes, and snippets.

@goodbyegangster
Last active March 21, 2024 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goodbyegangster/7481b760492267c449c25277fda9045c to your computer and use it in GitHub Desktop.
Save goodbyegangster/7481b760492267c449c25277fda9045c to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -Eeuo pipefail
trap finally SIGINT SIGTERM ERR EXIT
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
readonly SCRIPT_DIR
function usage() {
cat <<-EOF
Usage: $(basename "${BASH_SOURCE[0]}") [-h] [-v] [-p param_value] arg1 [arg2]
description.
Options:
-h, --help Print this help
-v, --verbose Print script debug info
-p, --param Some param description
Arguments:
arg1 aaaaa
arg2 bbbbb
EOF
}
function parse_args() {
while :; do
case ${1:-default} in
-h | --help) usage && exit ;;
-v | --verbose) set -x ;;
-p | --param)
local param="${2}"
shift
;;
-?*)
printf "\033[31m%s\033[m\n\n" "ERROR: unknown option" >&2
usage && exit 1
;;
*) break ;;
esac
shift
done
if [[ $# -eq 0 ]]; then
printf "\033[31m%s\033[m\n\n" "ERROR: missing arguments" >&2
usage && exit 1
fi
readonly PARAM=${param:-}
readonly ARG1=${1}
readonly ARG2=${2:-}
}
function finally() {
trap - SIGINT SIGTERM ERR EXIT
echo "cleanup done"
}
function main() {
parse_args "$@"
echo "$SCRIPT_DIR"
echo "$ARG1 $ARG2 $PARAM"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment