Details in my SO answer: https://stackoverflow.com/questions/11517139/optional-option-argument-with-getopts/57295993#57295993
getopts_get_optional_argument() {
eval next_token=\${$OPTIND}
if [[ -n $next_token && $next_token != -* ]]; then
OPTIND=$((OPTIND + 1))
OPTARG=$next_token
else
OPTARG=""
fi
}
Example usage:
while getopts "hdR" option; do
case $option in
d)
getopts_get_optional_argument $@
dir=${OPTARG}
;;
R)
getopts_get_optional_argument $@
level=${OPTARG:-1}
;;
h)
show_usage && exit 0
;;
\?)
show_usage && exit 1
;;
esac
done