diff --git a/SC2198.md b/SC2198.md new file mode 100644 index 0000000..f1dd3d4 --- /dev/null +++ b/SC2198.md @@ -0,0 +1,33 @@ +## Arrays don't work as operands in [ ]. Use a loop (or concatenate with * instead of @). + +### Problematic code: + +```sh +ext=png +allowedExt=(jpg bmp png) +[ "$ext" = "${allowedExt[@]}" ] && echo "Extension is valid" +``` + +### Correct code: + +```sh +ext=png +allowedExt=(jpg bmp png) +for value in "${allowedExt[@]}" +do + [ "$ext" = "$value" ] && echo "Extension is valid" +done +``` +### Rationale: + +Array expansions become a series of words in `[ .. ]`. Operators expect single words only. + +The problematic code is equivalent to `[ "$ext" = jpg bmp png ]`, which is invalid syntax. A typical error message is `bash: [: too many arguments` or `dash: somefile: unexpected operator`. + +Instead, use a `for` loop to iterate over values, and apply your condition to each. + +Alternatively, if you want to concatenate all the values in the array into a single string for your test, use `"$*"` or `"${array[*]}"`. + +### Exceptions: + +If you are dynamically building an a test expression, make your array the only thing in the test expression. ShellCheck will not emit a warning for: `set -- 1 -lt 2; [ "$@" ]` \ No newline at end of file