Shell Scripting – Why Use ‘while IFS= read’ Instead of ‘IFS=; while read’?

environment-variablesshelltext processing

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?

Best Answer

The trap is that

IFS=; while read..

sets the IFS for the whole shell environment outside the loop, whereas

while IFS= read

redefines it only for the read invocation (except in the Bourne shell). You can check that doing a loop like

while IFS= read xxx; ... done

then after such loop, echo "blabalbla $IFS ooooooo" prints

blabalbla
 ooooooo

whereas after

IFS=; read xxx; ... done

the IFS stays redefined: now echo "blabalbla $IFS ooooooo" prints

blabalbla  ooooooo

So if you use the second form, you have to remember to reset : IFS=$' \t\n'.


The second part of this question has been merged here, so I've removed the related answer from here.