Last active
December 4, 2018 20:33
-
-
Save ukayani/a27d1af5f5e0ec275e7bf44f9ce588e1 to your computer and use it in GitHub Desktop.
BashNamedArgs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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