mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2128 (markdown)
29
SC2128.md
Normal file
29
SC2128.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
## Expanding an array without an index only gives the first element.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
myarray=(foo bar)
|
||||||
|
for f in $myarray
|
||||||
|
do
|
||||||
|
cat "$f"
|
||||||
|
done
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
myarray=(foo bar)
|
||||||
|
for f in "${myarray[@]}"
|
||||||
|
do
|
||||||
|
cat "$f"
|
||||||
|
done
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
When referencing arrays, `$myarray` is equivalent to `${myarray[0]}` -- it results in only the first of multiple elements.
|
||||||
|
|
||||||
|
To get all elements as separate parameters, use the index `@` (and make sure to double quote). In the example, `echo "${myarray[@]}"` is equivalent to `echo "foo" "bar"`.
|
||||||
|
|
||||||
|
To get all elements as a single parameter, concatenated by the first character in `IFS`, use the index `*`. In the example, `echo "${myarray[*]}"` is equivalent to `echo "foo bar"`.
|
||||||
|
|
||||||
|
### Contraindications
|
||||||
|
|
||||||
|
None.
|
Reference in New Issue
Block a user