3

I am wondering why when you iterate over a variable n="1 2 3" you get this:

$ n="1 2 3"; for a in $n; do echo $a $a $a; done
1 1 1
2 2 2
3 3 3

but if you don't put the string in a variable first you get a completely different behaviour:

$ for a in "1 2 3"; do echo $a $a $a; done
1 2 3 1 2 3 1 2 3

or stranger yet:

$ for a in ""1 2 3""; do echo $a $a $a; done
1 1 1
2 2 2
3 3 3

why does it behave differently if a string is in a variable or not?

  • 3
    Because you're not quoting $n and your shell is doing word splitting. Try n="1 2 3"; for a in "$n"; do echo "$a" "$a" "$a"; done – don_crissti May 13 '16 at 23:37
  • Worth a read – iruvar May 14 '16 at 0:37
5
n="1 2 3"
for a in $n; do        # This will iterate over three strings, '1', '2', and '3'

for a in "1 2 3"; do   # This will iterate once with the single string '1 2 3'
for a in "$n"; do      # This will do the same

for a in ""1 2 3""; do # This will iterate over three strings, '""1', '2', and '3""'.  
                       # The first and third strings simply have a null string
                       # respectively prefixed and suffixed to them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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