1

Just a simple question.

I have an array:

array=("1 2 3" "4 5 6")

If I do:

echo ${array[0]}
echo ${array[1]}

1 2 3 or 4 5 6 will be shown.

However, if I do:

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

The shown value is not as I expected.... Can anyone give me the right way to use it?

1
  • What do you expect? I get "1 2 3" and "4 5 6", the values in the array. Commented Jul 15, 2013 at 15:18

1 Answer 1

4

Quotation is what you need:

for iter in "${array[@]}"; do 
  echo "$iter"
done
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the edit @chepner. Quoting the iter variable is not really needed, isn't it?
It depends. Unquoted, the value of $iter will undergo word-spliting before each word is passed as a separate argument to echo. Quoted, the entire string is passed as a single argument. Compare with something like iter="a b" (there are supposed to be multiple spaces between a and b).
@chepner Aah I can see the difference using for iter in "${array[@]}"; do printf "%s\n" $iter; done and for iter in "${array[@]}"; do printf "%s\n" "$iter"; done and yea that multiple spaces example is good to understand the reason too. Thanks again! :)
@HaoShen, the real magic here is quoting "${array[@]}" -- See gnu.org/software/bash/manual/bashref.html#Arrays and look for the paragraph containing "when the word appears within double quotes"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.