4
lis="a:b:c:d:"

IFS=:

If I run the following code,

for i in "a:b:c:d:";
do 
    echo the output is $i
done

I get:

the output is a b c d

If I replace "a:b:c:d:" with $lis instead:

for i in $lis;
do 
    echo the output is $i
done

I have the expected output:

the output is a
the output is b
the output is c
the output is d

I wonder what is wrong, $lis is basically the same as "a:b:c:d"

Jack Chen
  • 169

1 Answers1

2

The big difference is where word splitting is performed. Double quotes ensure that a literal string or quoted variable like "$lis" would be treated as single item

for i in "a:b:c:d:";
do 
    echo the output is $i
done

Therefore in this loop the double quoted "a:b:c:d:" is a single item, hence why you see only one line of output

the output is a b c d

for i in $lis;
do 
    echo the output is $i
done

Here the $lis is unquoted, hence the shell will perform word splitting according to the IFS value you've set. The shell will see there's 4 items provided to the for loop. Hence why you see four lines of output.

If you double quote "$lis" variable, the word splitting won't be performed, hence you should see identical output - only one line - to the first case.