0

Bash manual says

getopts optstring name [args]

When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument and name is set to ?.

In an example from the Bash Hackers Wiki getopts tutorial:

while getopts ":a" opt; do
  case $opt in
    a)
      echo "-a was triggered!" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

When the end of options is encountered, getopts exits with a return value greater than zero, so the while loop will stop. Then inside the while loop, is the part inside \?) never reached? If yes, why is it there?

Thanks.

5

It’s there to process invalid options. In the example, if you run script -a, the -a option is expected and results in “-a was triggered!”. If you run script -b, -b isn’t valid and will be handled by the \? case, resulting in “Invalid option: -b”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.