igor igor - 7 months ago 11
Bash Question

Escaping rules when reading in bash

Assume the file

text
is created as the following:

> cat > text
\abc
^D


The following two scripts generate different outputs and I don't understand why.

> s=$(cat text)
> echo $s
\abc
> cat text | while read line; do echo $line; done
abc


Why?

Answer

read without the -r option interprets backslash escapes, and \a becomes a. See the manual:

-r
If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.