Skip to content

Files

Latest commit

 

History

History
35 lines (24 loc) · 861 Bytes

SC2128.md

File metadata and controls

35 lines (24 loc) · 861 Bytes

Pattern: Expanding array without an index

Issue: -

Description

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

Further Reading