Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sh read command eats backslashes in input?

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?

like image 975
Jeremy Huiskamp Avatar asked May 29 '09 04:05

Jeremy Huiskamp


People also ask

How do you escape a backslash in shell script?

Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.

What is $@ in SH?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

Do Backslashes work in Linux?

Linux is a Unix-like operating system, so it uses the same type of slash. Mac OS X is based on BSD, another Unix-like operating system. Other consumer operating systems like Android, Chrome OS, and Steam OS are based on Linux, so they use the same type of slash.


2 Answers

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 \&| 
like image 124
Zsolt Botykai Avatar answered Sep 20 '22 03:09

Zsolt Botykai


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.

like image 38
Alex Martelli Avatar answered Sep 20 '22 03:09

Alex Martelli