title: Trapping getopt invalid options
body: <p>I'm using <code>getopt</code> (not <code>getops</code>) to provide the ability for my bash script to process options and switches (both long --option and short -o forms).</p>
  
  <p>I'd like to be able to trap invalid options and handle them, typically echoing out that the user should try <code>cmd --help</code> and then exiting the script.</p>
  
  <p>Thing is, the invalid options are being caught by getopt, which is itself outputting a message such as "getopt: invalid option -- 'x'"</p>
  
  <p>Here's the pattern I'm using to set my getopt parameters:</p>
  
  <pre><code>set -- $(getopt -o $SHORT_OPTIONS -l $LONG_OPTIONS -- "$@")
  </code></pre>
  
  <p>where both $LONG_OPTIONS and $SHORT_OPTIONS are a comma-delimited list of options.</p>
  
  <p>Here's how I handle processing the options:</p>
  
  <pre><code> while [ $# -gt 0 ]
      do
          case "$1" in
              -h|--help)
                  cat &lt;&lt;END_HELP_OUTPUT
  
      Help
      ----
  
      Usage: ./cmd.sh 
  
      END_HELP_OUTPUT
  
                  shift;
                  exit
                  ;;
              --opt1)
                  FLAG1=true
                  shift
                  ;;
              --opt2)
                  FLAG2=true
                  shift
                  ;;
              --)
                  shift
                  break
                  ;;
              *)
                  echo "Option $1 is not a valid option."
                  echo "Try './cmd.sh --help for more information."
                  shift
                  exit
                  ;;
          esac
      done
  </code></pre>
  
  <p><code>getopt -q</code> will suppress the output, but my trapping scheme within the <code>case</code> statement still fails to do what I expect. Instead, the program just executes, despite the invalid arguments.</p>