I have
$ IFS=123 $ myvar=abc1def1ghi $ for i in "$myvar"; do echo i $i; done i abc def ghi $ for i in $myvar; do echo i $i; done i abc i def i ghi $ myvar="abc1def1ghi" $ for i in "$myvar"; do echo i $i; done i abc def ghi $ for i in $myvar; do echo i $i; done i abc i def i ghi
I think I understand whats happening in 2nd and 4th for loops. But I do not understand why 1 was not printed in 1st and 3rd for loops. The whole idea of IFS is confusing to me in general.
Advertisement
Answer
When you say $var_name then 1 is interpreted as a separator and hence you see the string as cut into pieces.
$ IFS=123 $ myvar=abc1def1ghi $ echo $myvar abc def ghi
When you add quotes around the variable, you demand for the absolute value of the variable without any processing.
$ echo "$myvar" abc1def1ghi
Now coming to your question about 1st loop,
$ for i in "$myvar"; do echo i $i; done
is equivalent to
$ for i in "abc1def1gh1"; do echo i $i; done
‘i’ gets assigned “abc1def1gh1” and it prints out the value of variable ‘i’. This time ‘1’ is interpreted as a separator while printing ‘i’. This is what happened while running the loop:
$ i="abc1def1gh1" $ echo $i abc def gh
Same thing happens in the 3rd loop.
Now if you want ‘1’ to be printed, then add quotes around $i in the loop. ie. change this:
$ for i in "abc1def1gh1"; do echo i $i; done i abc def gh
to
$ for i in "abc1def1gh1"; do echo i "$i"; done i abc1def1gh1