Disabling whitespace trimming

It's important to note that by default, read ignores spaces and tabs at the start and end of a line when reading fields into variables:

$ cat lines
Line one
    Line two
  Line three
$ while read -r line ; do printf '%s\n' "$line" ; done
Line one
Line two
Line threedone <lines

A lot of the time, this is what you want, but if you do actually want the line literally in one variable including any leading and trailing spaces or tabs, you need to set IFS to a blank value for the read command:

$ while IFS= read -r line ; do printf '%s\n' "$line" ; done <lines
Line one
    Line two
  Line three

This also suppresses the field-splitting completely, of course, so you can only read the whole line into one variable this way.

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.