Skip to content

Instantly share code, notes, and snippets.

@finesse-fingers
Created May 4, 2020 09:10
Show Gist options
  • Save finesse-fingers/a64538e66dc00b0769fd3402a0c8e459 to your computer and use it in GitHub Desktop.
Save finesse-fingers/a64538e66dc00b0769fd3402a0c8e459 to your computer and use it in GitHub Desktop.
Demonstrates how to parse arguments in bash
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# -e: immediately exit if any command has a non-zero exit status
# -o: prevents errors in a pipeline from being masked
# IFS new value is less likely to cause confusing bugs when looping arrays or arguments (e.g. $@)
function usage()
{
echo "Usage: $0 args ..."
echo " -w, --workload <string> [required]"
echo " -l, --location <string> [default='australiaeast']"
echo " -h, --help <flag> [optional]"
echo " e.g.: $ $0 -w workload"
exit 1
}
# set help flag
declare help=0
# declare required params
declare workload="" # "someValue"
# decalre optional params
declare location="australiaeast"
# parse arguments
# https://gist.github.com/hfossli/4368aa5a577742c3c9f9266ed214aa58
# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
# best answer by Inanc Gumus edited by Michael
while [[ "$#" > 0 ]]; do case $1 in
-w|--workload) workload="$2"; shift;;
-l|--location) location="$2"; shift;;
-h|--help) help=1;;
*) echo "Unknown parameter passed: $1\n"; usage;;
esac; shift; done
# check for -h, --help flag and exit if present
if [ "$help" == 1 ]; then usage; fi;
# check required arguments
if [ "$workload" == "" ]; then
echo "-w, --workload is not set"
echo ""
usage
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment