5

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?

1 Answers1

7
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
DopeGhoti
  • 76,081