Skip to content

Instantly share code, notes, and snippets.

@heph
Created September 29, 2018 00:17
Show Gist options
  • Save heph/092a734241192bb53cc761e776f30f17 to your computer and use it in GitHub Desktop.
Save heph/092a734241192bb53cc761e776f30f17 to your computer and use it in GitHub Desktop.
How I start all my shell scripts
#!/usr/bin/env bash
#
# Short header explaining what the script does
#
# exit on error, error on unbound variables, disable glob expansion, fail within pipes
set -eufo pipefail
[[ -n "${DEBUG:-}" ]] && set -x
: "${VAR_A=default_value_a}"
: "${VAR_B=default_value_b}"
log() {
# Pro Tip: declare local before assignment (http://tldp.org/LDP/abs/html/localvar.html)
local level
local message
level="$(echo $1 | tr '[:lower:]' '[:upper:]')" ; shift
message=("$@")
# disable colorized output unless it's to a terminal
if [[ -t 1 ]]; then
local color
local reset
reset=$(echo -ne "\033[0m")
case $level in
ERR*) color=$(echo -ne "\033[91m") ;; # light red
WARN*) color=$(echo -ne "\033[93m") ;; # light yellow
OK*) color=$(echo -ne "\033[94m") ;; # light blue
INFO*) color=$(echo -ne "\033[97m") ;; # white
TASK*) color=$(echo -ne "\033[96m") ;; # light cyan
*) color=$(echo -ne "\033[39m") ;; # default
esac
echo "${color}[${level}]${reset} ${message}"
else
echo "[${level}] ${message}"
fi
}
main() {
log info "${FUNCNAME[0]} $@"
# Handle command line args and shift them out of $@ after use
while getopts 'a:b:' flag; do
case "${flag}" in
a) VAR_A="${OPTARG}" ;;
b) VAR_B="${OPTARG}" ;;
esac
done
shift $(($OPTIND - 1))
# Print usage
if [[ -z "$@" ]]; then
echo "Usage: $0 [-a <VAR_A>] [-b <VAR_B>] <arg> [<arg> ...]"
exit 1
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment