Skip to content

Instantly share code, notes, and snippets.

@aausch
Created June 3, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aausch/c199e9f9e60492a2df4b710162f5c3e5 to your computer and use it in GitHub Desktop.
Save aausch/c199e9f9e60492a2df4b710162f5c3e5 to your computer and use it in GitHub Desktop.
OSX/Bash argument parsing
#!/bin/bash -e
# cobbled together from various of stackoverflow posts
# saner programming env: these switches turn some bugs into errors
set -o errexit -o pipefail -o noclobber -o nounset
# -allow a command to fail with !’s side effect on errexit
# -use return value from ${PIPESTATUS[0]}, because ! hosed $?
! getopt --test > /dev/null
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
echo '`getopt --test` failed in this environment.'
echo 'On OSX, try the following commands'
echo ' brew install gnu-getopt'
echo ' sudo echo '"'"'export PATH="/usr/local/opt/gnu-getopt/bin:$PATH"'"'"'>> ~/.bash_profile'
echo ' sudo echo '"'"'export FLAGS_GETOPT_CMD="$(brew --prefix gnu-getopt)/bin/getopt"'"'"' >> ~/.bash_profile'
echo ' then run ". ~/.bash_profile"'
exit 1
fi
USAGE="$(basename "$0") [-h] [-e name]
where:
-h show this help text
-e/--environment set environment to attempt to deploy"
OPTIONS=dhe:o:v
LONGOPTS=debug,environment,output:,verbose
# -regarding ! and PIPESTATUS see above
# -temporarily store output to be able to check for errors
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
# -pass arguments only via -- "$@" to separate them correctly
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
# e.g. return value is 1
# then getopt has complained about wrong arguments to stdout
exit 2
fi
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"
d=n v=n environment=
while true; do
case "$1" in
-h|--help)
echo "$USAGE"
exit
;;
-d|--debug)
d=y
shift
;;
-v|--verbose)
v=y
shift
;;
-e|--environment)
environment="$2"
shift 2
;;
*)
break
;;
--)
shift
break
;;
esac
done
# TODO: print out help message? etc..
if [[ -z $environment ]]; then
echo "$0: Please input an environment name."
echo ""
echo "Usage:"
echo "$USAGE"
exit 4
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment