Optional option argument with getopts

This workaround defines ‘R’ with no argument (no ‘:’), tests for any argument after the ‘-R’ (manage last option on the command line) and tests if an existing argument starts with a dash.

# No : after R
while getopts "hd:R" arg; do
  case $arg in
  (...)
  R)
    # Check next positional parameter
    eval nextopt=\${$OPTIND}
    # existing or starting with dash?
    if [[ -n $nextopt && $nextopt != -* ]] ; then
      OPTIND=$((OPTIND + 1))
      level=$nextopt
    else
      level=1
    fi
    ;;
  (...)
  esac
done

Leave a Comment