Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active August 29, 2015 13:56
Show Gist options
  • Save coderofsalvation/8801742 to your computer and use it in GitHub Desktop.
Save coderofsalvation/8801742 to your computer and use it in GitHub Desktop.
snippet for getopts to easily support options and arguments in your shellscript
# snippet for getopts to easily support options and arguments in your shellscript
# usage: copy/paste it and run ./yourcommand -h foofoo -n barbar one two
# initialize variables
OPTION1="foo"
OPTION2="bar"
OPTIONS=0
# get rid of appname and (parse) options
shift
while getopts ":h:n:" opt
do
case ${opt} in
h) OPTION1=${OPTARG};((OPTIONS+=2));;
n) OPTION2=${OPTARG};((OPTIONS+=2));;
esac
done
for((i=0;i<OPTIONS;i++)); do shift; done
# initialize arguments
ARG1="$1"
ARG2="$2"
echo "-h=$OPTION1 -n=$OPTION2 ARG1=$ARG1 ARG2=$ARG2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment