Skip to content

Instantly share code, notes, and snippets.

@b1zzu
Last active February 3, 2021 12:33
Show Gist options
  • Save b1zzu/ccd9ef553d546a2009eca21ab45db97a to your computer and use it in GitHub Desktop.
Save b1zzu/ccd9ef553d546a2009eca21ab45db97a to your computer and use it in GitHub Desktop.
A simple template for bash scripts
#!/usr/bin/env bash
# Inspired from: https://gist.github.com/b1zzu/ccd9ef553d546a2009eca21ab45db97a
set -eEu -o pipefail
# shellcheck disable=SC2154
trap 's=$?; echo "$0: error on $0:$LINENO"; exit $s' ERR
SCRIPT=$0
# Defaults
# ---
DEFAULT_GLOBAL='some_default_value'
DEFAULT_DEMO_NAME='default value for the demo name option'
# Variables
# ---
GLOBAL=${GLOVAL:-${DEFAULT_GLOBAL}}
DEMO_NAME=${DEMO_NAME:-${DEFAULT_DEMO_NAME}}
# Help
# ---
function usage() {
echo
echo "Usage: ${SCRIPT} [OPTIONS] COMMAND"
echo
echo "Options:"
echo " --global string some global flag (default: ${DEFAULT_GLOBAL}) (env: GLOBAL)"
echo
echo "Commands:"
echo " demo print a demo message"
}
function demo_usage() {
echo
echo "Usage: ${SCRIPT} [GLOBAL_OPTIONS] demo [OPTIONS] MESSAGE"
echo
echo "Options:"
echo " --name string some name for the demo cmd (default: ${DEFAULT_DEMO_NAME}) (env: DEMO_NAME)"
}
# Utils
# ---
function fatal() {
echo "$SCRIPT: error: $1" >&2
return 1
}
function info() {
echo "$SCRIPT: info: $1" >&2
}
# Commands
# ---
function demo_command() {
# Positional Arguments
MESSAGE=
# Parse Command Arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help)
demo_usage
return 0
;;
--name)
DEMO_NAME="$2"
shift
shift
;;
--* | -*)
demo_usage
echo
fatal "unknown option '$1'"
;;
*)
MESSAGE="$1"
break
;;
esac
done
# Command
if [[ -z "${MESSAGE}" ]]; then
fatal "MESSAGE is required"
fi
info "execute the demo command"
echo "Demo invoked with:"
echo " GLOBAL: '${GLOBAL}'"
echo " DEMO_NAME: '${DEMO_NAME}'"
echo " MESSAGE: '${MESSAGE}'"
return 0
}
# Parse arguments
# ---
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help)
usage
exit 0
;;
--global)
GLOBAL="$2"
shift
shift
;;
demo)
shift
demo_command "$@"
exit 0
;;
--* | -*)
usage
echo
fatal "unknown option '$1'"
;;
*)
usage
echo
fatal "unknown command '$1'"
;;
esac
done
usage
echo
fatal "command not specified"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment