Skip to content

Instantly share code, notes, and snippets.

@AndrewGearhart
Last active June 16, 2023 12:35
Show Gist options
  • Save AndrewGearhart/463f84c8a5261e6c409d0c3a8e508228 to your computer and use it in GitHub Desktop.
Save AndrewGearhart/463f84c8a5261e6c409d0c3a8e508228 to your computer and use it in GitHub Desktop.
Bash Script Template
#!/usr/bin/env bash
# set -euo pipefail
IFS=$'\n\t'
#/ Usage:
#/ Version:
#/ Description:
#/ Examples:
#/ Options:
#/ --help: Display this help message
usage() { grep '^#/' "$0" | cut -c4- ; exit 0 ; }
expr "$*" : ".*--help" > /dev/null && usage
LOG_FILE="/tmp/$(basename "$0").log"
readonly LOG_FILE
LOG_TIMESTAMP_FORMAT='+%Y-%m-%d %H:%M:%S'
info() { echo "$(date $LOG_TIMESTAMP_FORMAT) [INFO] $*" | tee -a "$LOG_FILE" >&2 ; }
warning() { echo "$(date $LOG_TIMESTAMP_FORMAT) [WARNING] $*" | tee -a "$LOG_FILE" >&2 ; }
error() { echo "$(date $LOG_TIMESTAMP_FORMAT) [ERROR] $*" | tee -a "$LOG_FILE" >&2 ; }
fatal() { echo "$(date $LOG_TIMESTAMP_FORMAT) [FATAL] $*" | tee -a "$LOG_FILE" >&2 ; exit 1 ; }
cleanup() {
# Remove temporary files
# Restart services
# ...
return 0 # provided to allow clean-up to exist in template w/o causing errors while empty
}
# Parse Parameters #
UNCONSUMED=()
while [ "$#" -gt 1 ];
do
key="$1"
case $key in
#/ --discovery (-d): An example argument used to show how options are passed to the script.
-d|--discovery)
discovery_period="$2" # EXAMPLE
shift
;;
#/ --default: An example argument used to show how an option without a short option or value is coded.
--default)
default=YES
;;
*)
#/ Note: arguments without options are ignored without extra handling programmed
;;
esac
shift
done
set -- ${UNCONSUMED[@]} # UNCONSUMED becomes our new $@
if [[ "${BASH_SOURCE[0]}" = "$0" ]]; then
trap cleanup EXIT
# Script goes here
# ...
fi
@AndrewGearhart
Copy link
Author

Information on parsing command arguments and options was guided by this:
https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash/14203146#14203146

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment