From 3143e8d990ace35dc67dd2bd9a821dea1c7f61f4 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 19 Apr 2014 10:19:54 -0700 Subject: [PATCH] Created SC2128 (markdown) --- SC2128.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SC2128.md diff --git a/SC2128.md b/SC2128.md new file mode 100644 index 0000000..c74a890 --- /dev/null +++ b/SC2128.md @@ -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. \ No newline at end of file