Skip to content

Instantly share code, notes, and snippets.

@ukayani
Last active Dec 4, 2018
Embed
What would you like to do?
BashNamedArgs
#!/usr/bin/env bash
set -o pipefail
set -o nounset # fail on unset var usage
set -o errexit # exit on command failure
err_report() {
echo "Exited with error on line $1"
}
# prints errors out along with line number
trap 'err_report $LINENO' ERR
# changes bash word splitting to newline and tabs
IFS=$'\n\t'
function print_help {
echo "usage: $0 [options] <param>"
echo "Short Description"
echo ""
echo "-h,--help print this help"
echo "--param1 Description of param1"
echo "--param2 Description of param2"
}
# Create an array to store positional args
POSITIONAL=()
# loop over args one at a time
# always sets key to $1 since we keep shifting the args list to the left (if its key=value then shift left twice)
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-h|--help)
print_help
exit 1
;;
--param1)
PARAM_1="$2"
#shift twice. once for key, once for value
shift
shift
;;
--param2)
PARAM_2=$2
shift
shift
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
set +u #enable unset var usage
set -- "${POSITIONAL[@]}" # restore positional parameters
NAME="$1" #since positionals are restored, we can get first one
set -u #disable again
echo "Hello $NAME"
echo "Hello ${PARAM_2}" # this will error out if --param2 is not set
echo "Hello ${PARAM_2:-}" # This will not result in an error since ${PARAM_2:-} tests if the var is set first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment