Skip to content
Stavros Ntentos edited this page Feb 20, 2019 · 3 revisions

This pattern always overrides a later one.

Problematic code:

case "$1" in
  -?) echo "Usage: $0 [-n]";;
  -n) echo "Hello World";;
   *) exit 1;;
esac

Correct code:

case "$1" in
  -\?) echo "Usage: $0 [-n]";;
# '-?') echo "Usage: $0 [-n]";;  # Also valid
  -n) echo "Hello World";;
   *) exit 1;;
esac

Rationale:

You have specified multiple patterns in a case statement, where one will always override the other. The pattern being overridden is indicated with a SC2222 warning.

In the example, -? actually matches a dash followed by any character, such as -n. This means that the later -n branch will never trigger. In this case, the correct solution is to escape the -\? so that it doesn't match -n.

Another common reason for this is accidentally duplicating a branch. In this case, fix or delete the duplicate branch.

Exceptions:

None. One could argue that having -*|--*) echo "Invalid flag"; is a readability issue, even though the second pattern follows from the first. In this case, you can either rearrange the pattern from most to least specific, i.e. --*|-*) or ignore the error.

When ignoring this error, remember that ShellCheck directives have to go in front of the case statement, and not in front of the branch:

# shellcheck disable=SC2221,SC2222
case "$1" in
  -n) ...;;
  # no directive here
  -*|--*) echo "Unknown flag" ;;
esac

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally