#!/bin/bash
### preallocate variables
required=
optional_hasarg=
got_opt_arg=false
optional_noarg=false
has_default="DEFAULT"
### initialize (clear) opt parsing variables
OPTIND=
OPTARG=
opt=
while getopts "ha:b:cd:" opt; do
case "$opt" in
h)
echo "\
usage:
------
getoptsdemo [ -h ] -a REQ [ -b OPTHAS ] [ -c ] [ -d OPTDEF ]
description:
------------
This demonstrates parsing arguments with getopts
optional arguments:
-------------------
-h Print this help message and exit.
-a REQ Required opt that takes an argument.
-b OPTHAS Optional opt that takes an argument.
-c Optional opt that does not take an argument.
-d OPTDEF If given, sets value of has_default to OPTDEF.
Otherwise, the value of has_default defaults to
DEFAULT.
"
exit 0
;;
a)
required=${OPTARG}
;;
b)
optional_hasarg=${OPTARG}
got_opt_arg=true
;;
c)
optional_noarg=true
;;
d)
has_default=${OPTARG}
;;
?)
echo "Error: did not recognize option, ${OPTARG}."
echo "Please try -h for help."
exit 1
;;
esac
done
if [[ "$required" == "" ]]; then
echo "ERROR: Required option -a not set."
echo "Please try -h for help."
exit 1
fi
echo "required: $required"
if [[ "$got_opt_arg" == true ]]; then
if [[ "$optional_hasarg" == "" ]]; then
echo "-b option set but no argument given"
echo "Please try -h for help."
exit 1
else
echo "optional_hasarg: $optional_hasarg"
fi
else
echo "optional_hasarg not set"
fi
if [[ "$optional_noarg" == true ]]; then
echo "optional_noarg set"
else
echo "optional_noarg not set"
fi
echo "has_default: $has_default"