I understand that generally, the read shell builtin gets input and creates a variable which holds that input as a string in which backslashes would be just literal components and wouldn't escape anything anyway.
Plain read var
, without -r
, when given the input foo\bar
, would store in var
the string foobar
. It treats the backslash as escaping the following character, and removes the backslash. You'd need to enter foo\\bar
to get foo\bar
.
read
can be used to read multiple values, like so:
$ read a b <<< 'xx yy'; echo "<$a> <$b>"
<xx> <yy>
(<<<
is a "here-string", the following string is provided to the command as input.)
It uses the characters in IFS
as separators, so whitespace by default.
It's these separators that a backslash can be used to escape, making them regular characters, and removing the backslash, also if it appears in front of a regular character. So you'd get:
$ read a b <<< 'xx\ yy'; echo "<$a> <$b>"
<xx yy> <>
$ read a b <<< 'xx\n yy'; echo "<$a> <$b>"
<xxn> <yy>
Being able to escape the separators is seldom useful, and removing backslashes can also be annoying if someone wants to enter a string with C-style character escapes.
In addition, a backslash at the end of a line would make read
wait for another line to be read as a continuation of the first, similarly to how continuation lines work in C and in the shell.
With read -r
, backslashes are just a regular character:
$ read -r a b <<< 'value\with\backslashes\ yy'; echo "<$a> <$b>"
<value\with\backslashes\> <yy>
In many use cases, backslashes aren't something one would expect the user to input, and if there aren't any, read -r
is the same as plain read
. But in case someone were to (need to) input backslashes, using read -r
may reduce the surprises involved. Hence it's probably good to use it, unless you really know you want them to be special for read
(in addition to whatever special properties your program might otherwise assign to them).
read
without-r
and without explicitly setting$IFS
for that oneread
invocation to the list of delimiters you wantread
to use to delimit words (or the empty string, if you don't want splitting).-e
option (similar to what Dennis Ritchie did toecho
in V8 in the early 80s), but unfortunately that was later reverted as portability with the Bourne shell was deemed more important than a cleaner design.