From 8d813e476483988a5ab784f6b15472bda08a8b1f Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 16 Sep 2017 13:02:58 -0700 Subject: [PATCH] Created SC2220 (markdown) --- SC2220.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 SC2220.md diff --git a/SC2220.md b/SC2220.md new file mode 100644 index 0000000..eb215ca --- /dev/null +++ b/SC2220.md @@ -0,0 +1,41 @@ +## Invalid flags are not handled. Add a `*)` case. + +### Problematic code: + +```sh +#!/bin/sh +while getopts "vr" f +do + case "$f" in + v) echo "verbose" ;; + r) echo "recursive" ;; + esac +done +``` + +### Correct code: + +```sh +#!/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 +``` + +### Rationale: + +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. + +### Exceptions: + +If your script's logic handles unrecognized flags in another way, e.g. after the `case` statement, you can ignore this warning. \ No newline at end of file