2

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
peaqe
  • 23
  • 3
  • And I still confused that why $data (quoted and unquoted) has different result in first script. – peaqe Dec 04 '22 at 11:11
  • There is no `$data` in the second script. – M. Nejat Aydin Dec 04 '22 at 11:27
  • 1
    [@M.NejatAydin's answer](https://stackoverflow.com/a/74674566/1745001) tells you exactly why. If it's not clear you should ask them to clarify whatever point is unclear. Also, do `set -x` before running both command lines to see what they actually do. – Ed Morton Dec 04 '22 at 11:28

2 Answers2

2

@HaimCohen explained in detail why you get a different result with those two approaches. Which is what you asked. His answer is correct, it should get upvoted and accepted.

Just a trivial addition from my side: you can easily modify the second of your approaches however if you define the variable on the fly:

IFS=",";for i in ${var="a,b,c"};do echo $i;done
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • [HaimCohen's answer](https://stackoverflow.com/a/74674364/1745001) states WHAT happens, t doesn't explain WHY it happens. [M. Nejat Aydin's answer](https://stackoverflow.com/a/74674566/1745001) explains WHY ("Word splitting is performed on the results of unquoted expansions"). – Ed Morton Dec 04 '22 at 12:06
2

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.

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17