Skip to content

Instantly share code, notes, and snippets.

@stuarthendren
Last active May 8, 2018 15:15
Show Gist options
  • Save stuarthendren/7241912 to your computer and use it in GitHub Desktop.
Save stuarthendren/7241912 to your computer and use it in GitHub Desktop.
Bash template
#!/usr/bin/env bash
set -euo pipefail
IFS=$' \n\t'
# To source a dependency
#. dependency
# Script directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEFAULT_VALUE="default"
usage() {
echo -e ""
echo -e "Usage: \\x1B[1m myscript [-o <option> ] [-d <default>] [-f] [-h]"
echo -e "\\x1B[0m"
echo -e "\\tDescription of script"
echo -e ""
echo -e "Options:"
echo -e ""
echo -e " -o | --option \\t parameter with value"
echo -e " -d | --default \\t parameter that defaults to $DEFAULT_VALUE"
echo -e " -f | --flag \\t a flag parameter"
echo -e " -h | --help \\t show the help"
}
value=$DEFAULT_VALUE
option=
flag=0
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-o | --option ) shift
option=$1
;;
-d | --default ) shift
value=$1
;;
-f | --flag ) flag=1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done
readonly LOG_FILE="/tmp/$(basename "$0").log"
section() { text="
###########################################################
# $*
###########################################################
"
echo "$text" | tee -a "$LOG_FILE" >&2 ; }
info() { echo "[INFO] $*" | tee -a "$LOG_FILE" >&2 ; }
warn() { echo "[WARNING] $*" | tee -a "$LOG_FILE" >&2 ; }
error() { echo "[ERROR] $*" | tee -a "$LOG_FILE" >&2 ; }
fatal() { echo "[FATAL] $*" | tee -a "$LOG_FILE" >&2 ; exit 1 ; }
cleanup() {
section Trap
# Remove temporary files
# Restart services
# ...
info cleaning up
}
if [[ "${BASH_SOURCE[0]}" = "$0" ]]; then
trap cleanup EXIT
# Script goes here
# ...
section Running Script
warn "Directory of script $DIR"
info "value $option"
info "value $value"
info "flag $flag"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment