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"
1 Answer 1
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.
-
12How can you set
IFS
only within the scope of thefor
block?Mehdi Charife– Mehdi Charife2023年02月21日 02:28:24 +00:00Commented Feb 21, 2023 at 2:28 -
a:b:c:d:
is a literal, regardless if quotes are used or not. So in this case, the issue doesn't have anything to do with the quotes, but rather with the fact word splitting doesn't apply to literals.David Ongaro– David Ongaro2024年04月25日 22:55:42 +00:00Commented Apr 25, 2024 at 22:55
"$lis"
might be, but$lis
isn't.