mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2199 (markdown)
30
SC2199.md
Normal file
30
SC2199.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
## Arrays implicitly concatenate in [[ ]]. Use a loop (or explicit * 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 in `[[ .. ]]` will implicitly concatenate into a single string, much like in assignments. The problematic code is equivalent to `[ "$ext" = "jpg bmp png" ]`.
|
||||||
|
|
||||||
|
Instead, use a `for` loop to iterate over values, and apply your condition to each.
|
||||||
|
|
||||||
|
Alternatively, if you do want to concatenate all the values in the array into a single string for your test, use `"$*"` or `"${array[*]}"` to make this explicit.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
None.
|
Reference in New Issue
Block a user