Skip to content

Files

Latest commit

 

History

History
39 lines (26 loc) · 1.12 KB

SC2198.md

File metadata and controls

39 lines (26 loc) · 1.12 KB

Pattern: Array expansion in [ .. ]

Issue: -

Description

Array expansions become a series of words in [ .. ]. Operators expect single words only.

Example of incorrect code:

ext=png
allowedExt=(jpg bmp png)
[ "$ext" = "${allowedExt[@]}" ] && echo "Extension is valid"

This 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[*]}".

Example of correct code:

ext=png
allowedExt=(jpg bmp png)
for value in "${allowedExt[@]}"
do
  [ "$ext" = "$value" ] && echo "Extension is valid"
done

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; [ "$@" ]

Further Reading