Skip to content

Instantly share code, notes, and snippets.

@bcawrse
Last active Jun 22, 2021
Embed
What would you like to do?
Template for writing new scripts
#!/bin/bash
#scriptName.sh
# Bash scripting reference manual
# - http://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html
# Bash script set options
# - https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
set -o errexit
set -o errtrace
set -o pipefail
# Parameter expansion reference for "${1#*=}" etc
# - http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion
############################################################
# Help #
############################################################
Help()
{
# Display Help
echo "Add description of the script functions here."
echo
echo "Syntax: scriptTemplate [-h | --help] [-e value | --echo value] [-v]"
echo "options:"
echo " h Print this help and exit."
echo " e Echo value."
echo " v Verbose mode set for echo parameter."
echo
echo "Note: parameters must be separated, such as -h -e -v, but order does not matter."
}
############################################################
# Main Program #
############################################################
# display Help when nothing provided
if [ $# -eq 0 ]; then
Help; exit 0;
fi
# iterate over parameters
while [ $# -gt 0 ]; do
case "$1" in
# help flag
-h | --help)
Help
exit
;;
# argument flag - requires value
-e | --echo)
if [[ "$1" != *=* ]]; then shift; fi # value is next arg if no '=' in parameter
E="${1#*=}"
if [[ -z $E ]]; then echo "Value not provided for -e"; exit 1; fi
;;
# option flag
-v | --version)
V=true
;;
# catch the rest
*)
echo "Error: Invalid argument \"$1\""
echo ""
Help
exit 1
;;
esac
shift
done
if [[ ! -z $E ]]; then
if [[ "$V" = true ]]; then
echo "verbose mode!"
fi
echo "$E"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment