bashfor-loopdouble-quotesifs

why there is different output in for-loop


Linux bash: why the two shell script as follow had different result?

[root@yumserver ~]# data="a,b,c";IFS=",";for i in $data;do echo $i;done
a
b
c
[root@yumserver ~]# IFS=",";for i in a,b,c;do echo $i;done                     
a b c

expect output: the second script also output:

a
b
c

I should understood what @M.NejatAydin means。Thanks also @EdMorton,@HaimCohen!

[root@k8smaster01 ~]# set -x;data="a,b,c";IFS=",";echo $data;echo "$data";for i in $data;do echo $i;done
+ data=a,b,c
+ IFS=,
+ echo a b c
a b c
+ echo a,b,c
a,b,c
+ for i in '$data'
+ echo a
a
+ for i in '$data'
+ echo b
b
+ for i in '$data'
+ echo c
c
[root@k8smaster01 ~]# IFS=",";for i in a,b,c;do echo $i;done                    
+ IFS=,
+ for i in a,b,c
+ echo a b c
a b c

Solution

  • Word splitting is performed on the results of unquoted expansions (specifically, parameter expansions, command substitutions, and arithmetic expansions, with a few exceptions which are not relevant here). The literal string a,b,c in the second for loop is not an expansion at all. Thus, word splitting is not performed on that literal string. But note that, in the second example, word splitting is still performed on $i (an unquoted expansion) in the command echo $i.

    It seems the point of confusion is where and when the IFS is used. It is used in the word splitting phase following an (unquoted) expansion. It is not used when the shell reads its input and breaks the input into words, which is an earlier phase.

    Note: IFS is also used in other contexts (eg, by the read builtin command) which are not relevant to this question.