read -r是什么意思?


21

为了了解另一个答案:

find / -type d -print0 | while read -r -d ''; do ls -ltr "$dir" | sed '$!d'

第一步是了解read命令的-r选项的用法。

首先,我认为只需执行即可

man read

查找-r选项的含义,但是我意识到手册页根本不包含对选项的任何解释,因此我用谷歌搜索了一些read -t,read -p示例,但没有read -r。


您是说没有供阅读的手册页吗?如果我输入man read,我会得到一长串的Bash内置命令。我使用“ / read”进行搜索,然后将看到的内容
粘贴

1
这是一个内置的外壳(至少使用bash help readman bash
格式


READ(1P)对我而言存在...
jasonwryan

Answers:


27

没有独立的read命令:相反,它是内置的shell,因此在手册页中针对bash

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p
prompt] [-t timeout] [-u fd] [name ...]
[...]
       -r     Backslash does not act as an escape character.  The back‐
              slash is considered to be part of the line.  In  particu‐
              lar,  a  backslash-newline pair may not be used as a line
              continuation.

因此,总而言之,read通常允许使用尾随反斜杠字符来折断长行,并通常重新构造此类行。可以使用停用此稍微令人惊讶的行为-r


10
演示:str="a\bc"; read x <<< "$str"; read -r y <<< "$str"; echo "$x"; echo "$y"
格伦·杰克曼(Glenn Jackman)

@glennjackman太好了,如果您输入b`会更引人注目str="a` and then hit Enter before pasting in the rest of the command starting with
ErikE

1

-r选项可防止反斜杠转义被解释。这是一个例子:

假设有一个文件包含以下内容:

ngRTM6hNqgziZcqCcEJN7bHAP9a1GeMs\
Ni3EAX1qvogWpRIPE3oagJL6nwl\QQW9y
bjJHyaVBrUcyZOY5U4h9QHnpEPqg\\\\\\\\\Q9Fk
iNOvAyBTAcN5n1uwR4GvRfAGUbPWiXax\n
cqGPPStH3gaWolrfVAlMtoWiSuLa7GzQ\n\n\n
EnO04N1nEkpWbfXRxrtYNqCZDpF\trQIXS
$ while read line; do echo $line; done < tempfile
ngRTM6hNqgziZcqCcEJN7bHAP9a1GeMsNi3EAX1qvogWpRIPE3oagJL6nwlQQW9y
bjJHyaVBrUcyZOY5U4h9QHnpEPqg\\\\Q9Fk
iNOvAyBTAcN5n1uwR4GvRfAGUbPWiXaxn
cqGPPStH3gaWolrfVAlMtoWiSuLa7GzQnnn
EnO04N1nEkpWbfXRxrtYNqCZDpFtrQIXS
$ while read -r line; do echo $line; done < tempfile
ngRTM6hNqgziZcqCcEJN7bHAP9a1GeMs\
Ni3EAX1qvogWpRIPE3oagJL6nwl\QQW9y
bjJHyaVBrUcyZOY5U4h9QHnpEPqg\\\\\\\\\Q9Fk
iNOvAyBTAcN5n1uwR4GvRfAGUbPWiXax\n
cqGPPStH3gaWolrfVAlMtoWiSuLa7GzQ\n\n\n
EnO04N1nEkpWbfXRxrtYNqCZDpF\trQIXS
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.