Skip to content

Latest commit

 

History

History
49 lines (35 loc) · 1.22 KB

SC2220.md

File metadata and controls

49 lines (35 loc) · 1.22 KB

Pattern: Unhandled error case in getopt loop

Issue: -

Description

Invalid flags are not handled. Add a *) case.

Example of incorrect code:

#!/bin/sh
while getopts "vr" f
do
  case "$f" in
    v) echo "verbose" ;;
    r) echo "recursive" ;;
  esac
done

The case statement handling getopts arguments does not have a default branch to handle unknown flags.

When a flag is not recognized, such as if passing -Z to the example code, getopts will set the variable to a literal question mark ?. This should be handled along with all the valid flags, usually by printing a usage message and exiting with failure.

Using a \?) or ?) case will also match invalid flags, but*) would additionally match things like the empty string if the variable name was misspelled.

Example of correct code:

#!/bin/sh
while getopts "vr" f
do
  case "$f" in
    v) echo "verbose" ;;
    r) echo "recursive" ;;
    *) echo "usage: $0 [-v] [-r]" >&2
       exit 1 ;;
  esac
done

Exceptions

If your script's logic handles unrecognized flags in another way, e.g. after the case statement, you can ignore this warning.

Further Reading