39

Perhaps easiest to explain with an example:

$ echo '\&|'
\&|
$ echo '\&|' | while read in; do echo "$in"; done
&|

It seems that the read command is interpreting the backslashes in the input as escapes and is removing them. I need to process a file line by line without changing its contents and I'm not sure how to stop read from being smart here. Any ideas?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Jeremy Huiskamp
  • 5,186
  • 5
  • 26
  • 19

2 Answers2

56

Accrding to: http://www.vias.org/linux-knowhow/bbg_sect_08_02_01.html :

-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.

It works on my machine.

$ echo '\&|' | while read -r in; do echo "$in"; done
\&|
Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110
  • 1
    Awesome, thanks! I feel dumb for not having found the documentation for this, but it's one of those things that's hard to search for because the terms are rather generic :( – Jeremy Huiskamp May 29 '09 at 04:57
  • Btw, what shell are you using that does not require the -r? I'm using bash. – Jeremy Huiskamp May 29 '09 at 04:59
  • Watch out that this is not exactly true for read on zsh: [documentation of built-in commands](http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html). Difference: -r just prints '\' if it is at the _end_ of the line. So `read -r in && echo $in` will echo two lines if you enter `foo\nbar` – normanius Dec 11 '15 at 16:32
  • 1
    @normanius the difference is not in `read`, it's in `echo` - the zsh built in `echo` converts escape sequences like `\n` by default, whereas the bash built in you have to opt in to escape processing with `echo -e` – Ian Roberts Aug 15 '23 at 17:45
7

Use read -r, as per http://www.ss64.com/bash/read.html:

-r
If this option is given, backslash does not act as an escape character.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395