Home > OS >  why there is different output in for-loop
why there is different output in for-loop

Time:12-04

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

CodePudding user response:

@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

CodePudding user response:

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.

CodePudding user response:

The difference between the two scripts is how the input data is provided to the for loop. In the first script, the input data is stored in a variable named "data" and is passed to the for loop using the $data syntax. In the second script, the input data is directly provided to the for loop using the "a,b,c" syntax.

When using the $data syntax, the IFS (Internal Field Separator) is applied to the input data, splitting it into separate items based on the specified delimiter (in this case, a comma). This allows the for loop to iterate over each individual item in the input data, resulting in the output of "a", "b", and "c" on separate lines.

In the second script, however, the IFS is not applied to the input data because it is not passed through a variable. As a result, the for loop treats the input data as a single item and outputs it as one string, resulting in the output of "a b c" on the same line.

  • Related