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
sets the
redefines it only for the
then after such loop,
whereas after
the
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. |
|||||||||||
|
|
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 So, in order to read each line literally, we need to make sure that no word splitting is going on. We do this by setting the
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. See also: Bash, read line by line from file, with IFS
|
|||
|
|
|
Inspired by Yuzem’s answer If you want to set
|
||||
|
|
