IFS is used as word splitting characters but what exactly happens when IFS is null/empty. For instance , consider the input file abc.txt with contents
first line
second line
now , if I run
IFS='' # or IFS= or assume IFS is null
for word in $(cat abc.txt)
do
echo ${word}
done
Then the output is
first line
second line
notice , in output , two lines had been shown. Now , the question is why two lines are showing up instead of one? If no IFS is being used as word splitting character then I guess the output should be
first line second line
Shouldn't the output be in a single line only , since \n is also not a IFS at this moment?
You have IFS set but to an empty value.
Assuming you are using a POSIX-compliant shell, if IFS is empty, as per IEEE Std 1003.1, 2004 (minor update to POSIX.1-2001) section 2.6.5 Field Splitting says:
If the value of IFS is null, no field splitting shall be performed.
So you are actually not iterating over the lines, just printing all in one run. If relevant, please note that unsetting IFS will have a very different behaviour (making it behave as if it was filled with the defaults, space/tab/newline).
The entire contents of abc.txt are assigned to word in the first iteration of the loop, including the linefeeds at the end of each line. Those linefeeds are part of the argument to echo, which writes them to standard output.
Your loop executes exactly once, with the single call to echo writing the two lines read from the file.
(Add declare -p word to the body of the loop to see the full value of word in the one and only iteration.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With