Skip to content

Instantly share code, notes, and snippets.

@jacknlliu
Forked from cosimo/parse-options.sh
Last active August 4, 2017 09:53
Show Gist options
  • Select an option

  • Save jacknlliu/7c51e0ee8b51881dc8fb2183c481992e to your computer and use it in GitHub Desktop.

Select an option

Save jacknlliu/7c51e0ee8b51881dc8fb2183c481992e to your computer and use it in GitHub Desktop.
Example of how to parse options with bash/getopt
#!/bin/bash
#
# Example of how to parse short/long options with 'getopt'
#
# getopt recognize the params and put unrecognize params after '--', so '--' is a very important flag for latter work.
# -o for options like: -v -h -n -s
# --long for options like: --verbose --dry-run --help --stack-szie
# and which options followed by a ':' will have format like -s 3, --stack-size 4 or -s=3 --stack-size=4
# -n: name of the shell script
OPTS=`getopt -o vhns: --long verbose,dry-run,help,stack-size: -n 'parse-options' -- "$@"`
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
echo "$OPTS"
# get every positional params. for example, "a b" "c d" will be $1="a", $2="b", $3="c", $4="d"
eval set -- "$OPTS"
VERBOSE=false
HELP=false
DRY_RUN=false
STACK_SIZE=0
# shift will go to next position param.
while true; do
case "$1" in
-v | --verbose ) VERBOSE=true; shift ;;
-h | --help ) HELP=true; shift ;;
-n | --dry-run ) DRY_RUN=true; shift ;;
-s | --stack-size ) STACK_SIZE="$2"; shift; shift ;;
-- ) shift; break ;;
* ) if [ -z "$1" ]; then break; else echo "$1 is not a valid option"; exit 1; fi;;
esac
done
echo VERBOSE=$VERBOSE
echo HELP=$HELP
echo DRY_RUN=$DRY_RUN
echo STACK_SIZE=$STACK_SIZE
@jacknlliu
Copy link
Author

An additional example, see here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment