It seems that normal practice would put the setting of IFS outside the while loop in order to not repeat setting it for each iteration... Is this just a habitual "monkey see, monkey do" style, as it has been for this monkey until I read man read, or am I missing some subtle (or blatantly obvious) trap here?
The trap is that
redefines it only for the
then after such loop,
So if you use the second form, you have to remember to reset :
The second part of this question has been merged here, so I've removed the related answer from here.
|show 3 more comments|
Let's look at an example, with some carefully-crafted input text:
That's two lines, the first beginning with a space and ending with a backslash. First, let's look at what happens without any precautions around
That's better, we have two lines as expected. The two lines almost contain the desired content: the double space between
Note how we set
Thus we're taking care not to change the value of
Contrast with this code snippet, which looks files up in a colon-separated path. The list of file names is read from a file, one file name per line.
If the loop was
Of course, it would be possible to restore the value of
¹ And, if
Apart from the (already clarified)
This can have pretty serious consequences if file paths are being processed.
Therefore setting the IFS variable to the empty string is anything but a bad idea since it ensures that a line's leading and trailing whitespace does not get stripped.
Inspired by Yuzem’s answer
If you want to set