0

Given an array of two elements,

array=("foo bar" baz)

Using a for..in loop with the "normal" syntax yields three iterations (elements of the array are expanded).

for element in ${array[@]}
do echo $element
done

Output:

foo
bar
baz

While a for..in loop with the "index" syntax works as intended (elements are not expanded).

for i in ${!array[@]}
do echo ${array[i]}
done

Output:

foo bar
baz

Is there any way to use the first syntax construct as I intend (i.e. to get the same results as those I get using the second construct)?

GNU bash, version 4.1.2(1)-release

2 Answers 2

4

Quotes make the difference, so you need to update your code to the following:

for element in "${array[@]}"
do
   echo $element
done

Note

for element in "${array[@]}"
               ^           ^

instead of

for element in ${array[@]}

Test

$ array=("foo bar" baz)
$ for element in "${array[@]}"; do echo $element; done
foo bar
baz
2

Did you try:

for element in "${array[@]}"; do 
  echo "${element}"
done

The manual would tell:

IFS is a list of characters that separate fields; used when the shell splits words as part of expansion.

Doing:

IFS=$''
for element in ${array[@]}; do 
  echo "${element}"
done

would also give the expected result.

4
  • Just curious, is $'' a typo? (Sorry by the way, I think fedorqui pulled the trigger a little faster ;))
    – tne
    Commented Aug 19, 2013 at 13:26
  • @user2266481 No, it's not a typo. It resets IFS so that word splitting would not be performed when whitespaces are encountered.
    – devnull
    Commented Aug 19, 2013 at 13:28
  • Okay, I was actually wondering about the dollar sign, which I've never used to set IFS or to prefix an empty string. Things seem to work out fine without it, could you expand a little bit on it?
    – tne
    Commented Aug 19, 2013 at 13:31
  • 1
    @user2266481 Using $'' makes bash interpret escape sequences within ''. So you could conveniently say things like $'\t\n' ...
    – devnull
    Commented Aug 19, 2013 at 13:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.