getopt
Generally speaking, use getopts
since it is newer and a built-in function of bash. Use getopt
if you are looking for consistency across platforms.
The man page has a good example, but here are some of the basics:
Use -a: to requires an argument, either directly after the -a
or with a whitespace first.
getopt a: $*
Use -b to set a boolean value.
getopt b $*
getopt example
# Allow -a <arg>, -d and -z args=`getopt a:vz $*` # If getopt fails, then throw an error and quit if [ $? -ne 0 ]; then echo "Usage: ... "; exit 1; fi # Set the new arguments set -- $args while true; do case "$1" in -a) echo "Passed '$2' argument to -a"; shift; shift;; -v) echo "Verbose output enabled"; verbose=1; shift;; -z) echo "Debug output enabled"; verbose=1; debug=1; shift;; --) shift; break;; esac done