SC2213 – ShellCheck Wiki

See this page on GitHub

Sitemap


getopts specified -n, but it's not handled by this case.

Problematic code:

while getopts "vrn" n
do
  case "$n" in
    v) echo "Verbose" ;;
    r) echo "Recursive" ;;
    \?) usage;;
  esac
done

Correct code:

while getopts "vrn" n
do
  case "$n" in
    v) echo "Verbose" ;;
    r) echo "Recursive" ;;
    n) echo "Dry-run" ;;    # -n handled here
    \?) usage;;
  esac
done

Rationale:

You have a while getopts loop where the corresponding case statement fails to handle one of the flags.

Either add a case to handle the flag, or remove it from the getopts option string.

Exceptions:

ShellCheck may not correctly recognize less canonical uses of while getopts ..; do case ..;, such as when modifying the variable before using it:

while getopts "rf-:" OPT; do
  if [ "$OPT" = "-" ]; then   # long option: reformulate OPT and OPTARG
    OPT="${OPTARG%%=*}"       # extract long option name
    OPTARG="${OPTARG#$OPT}"   # extract long option argument (may be empty)
    OPTARG="${OPTARG#=}"      # if long option argument, remove assigning `=`
  fi

  case "$OPT" in
    r) ... ;;
    f) ... ;;
    my-long-option) ... ;;
  esac
done

In such cases you can do one of:


ShellCheck is a static analysis tool for shell scripts. This page is part of its documentation.