Skip to content

Instantly share code, notes, and snippets.

@brockers
Created March 13, 2019 04:14
Show Gist options
  • Save brockers/b7b08f9b534edf0a026009094d2a7bfc to your computer and use it in GitHub Desktop.
Save brockers/b7b08f9b534edf0a026009094d2a7bfc to your computer and use it in GitHub Desktop.
Some of the more useful design elements I put into any bash script that is going to be used more than once
#!/usr/bin/env bash
set -euo pipefail
# Enablig debug if DEBUG environment variable
${DEBUG:+set -x}
declare -a OVERRIDE_VALS
# Define script file path
REALPATH="$(dirname "$(realpath "$0")")"
# GLOBAL VARIABLES
NORMAL_THINGS=""
DEFAULT_THINGS=${DEFAULT_THINGS:-"SOME_DEFAULT_VALUE"}
# Text Colors and Messaging Functions
scriptName=$(basename "$0")
textReset=$(tty -s && tput sgr0 || echo " ")
textRed=$(tty -s && tput setaf 1 || echo "!!!")
textGreen=$(tty -s && tput setaf 2 || echo " ")
textYellow=$(tty -s && tput setaf 3 || echo "???")
m_input () {
# shellcheck disable=SC1087
echo -n "$textGreen[$scriptName]$textReset $1"
}
m_info () {
# shellcheck disable=SC1087
echo "$textGreen[$scriptName]$textReset $1"
}
m_warning () {
# shellcheck disable=SC1087
echo "$textYellow[$scriptName]$textReset $1"
}
m_error () {
# shellcheck disable=SC1087
echo "$textRed[$scriptName]$textReset $1"
}
usage(){
m_info ""
m_info "Script for doing something that is described here"
m_info ""
m_info "USAGE: $scriptName [OPTIONS] <TEMPLATE>"
m_info ""
m_info "Options:"
m_info " "
m_info " -a ...Some option described her when passing a."
m_info " This is useful when as STDOUT to another program."
m_info ""
m_info " -h ...Short HELP screen (this one)."
m_info ""
m_info "Examples:"
m_info ""
m_info " $scriptName -x something ...Short examples for using script"
}
test_program_availability(){
local APP
APP="${1}"
type "${APP}" >/dev/null 2>&1 ||
m_error "Required application: ${APP} is missing"
}
# Check to see if any external application dependancies are missing
test_program_availability 'aws'
# Check to see if no options were passed
if [ -z "${1:-}" ]; then usage; fi
# options with : require an argument, otherwise not
while getopts hC:c: OPT; do
case "$OPT" in
C|c)
GET_C_OPTION=$OPTARG
# Do something with GET_C_OPTION
;;
h)
usage
;;
*)
usage
break
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment