Are you the author of this? And why exactly did you post it? What context? Do you have a question, are you looking for comments, or are you just doing this to help others?
In any case, this is incorrect:
Quote:
Although the while loop is the easiest method, it has its side effects. It obliterates the formatting of lines including spaces and tabs.
|
A
while+read loop saves everything up to the next line delimiter exactly as it appears in the original. All whitespace other than the newline itself (the line delimiter) is preserved. It only ever breaks anything else up if you supply
read with multiple variables as arguments, in which case it divides the line up according to the setting of IFS.
In fact, it's the
for loop that comes out worse here. Preserving line formatting requires awkwardly working around the natural behavior of the shell, and even then you can
never preserve completely blank lines unless you also forgo using the newline as a delimiter.
The
for loop is also less efficient, as the entire file has to be read into memory before the loop is ever run. Not to mention that it generally relies on the external
cat command, which means even more overhead (
bash allows you to replace it with
$(<file) but that's a non-portable extension).
These two pages cover the reading of files in the shell in much more detail than the above:
Don't Read Lines With For
How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
In short, a
while+read loop is always the preferred way to read a file or any other input that consists of lines of complex text.