Pattern: Expanding array without an index
Issue: -
When referencing arrays, $somearray
is equivalent to ${somearray[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 "${somearray[@]}"
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 "${somearray[*]}"
is equivalent to echo "foo bar"
.
Example of incorrect code:
somearray=(foo bar)
for f in $somearray
do
cat "$f"
done
Example of correct code:
somearray=(foo bar)
for f in "${somearray[@]}"
do
cat "$f"
done