Search code examples
shellswitch-statementparameter-passinggetopts

How to show ALL the invalid options entered when getopts is used?


I have written a script myscript:

while getopts "t:" opt; do
  case ${opt} in
    t )
      target=$OPTARG
      ;;
   
    * )
      echo "Invalid option: $OPTARG requires an argument" 
      exit 1;
      ;;
  esac
done
shift $((OPTIND -1))

If I enter an input like

$ myscript -eio

It ONLY displays

Invalid option: e 

I want it to display all of the INVALID options I passed, like:

Invalid option: e
Invalid option: i
Invalid option: o

I've used exit 1 to exit the script showing invalid options and I don't want the script to execute any further.But if I don't use it, it'll show ALL the invalid options HOW I WANT but, the script will execute further, which I don't want.

Please do help. Thanks.


Solution

  • Use a helper variable, invalid that records any invalid option. Once the option parsing loop is done, test it.

    invalid=false
    while getopts "t:" opt; do
      case ${opt} in
        (t)
          target=$OPTARG
          ;;
       
        (*)
          echo "Invalid option: $OPTARG requires an argument" 
          invalid=true
          ;;
      esac
    done
    case $invalid in
       (true) exit 1;;
    esac
    
    shift $((OPTIND -1))