简体   繁体   English

bash而读取循环失败,以\\作为行终止

[英]bash while read loop fails with \ as line termination

Input file: 输入文件:

$ cat list 
dog \
cat \
apple \

script: 脚本:

while read line;do echo $line;done < list;

The Problem: The above script prints nothing. 问题:上面的脚本什么都不打印。 Whereas using 'read -r' in place of read prints all lines. 而使用'read -r'代替read会打印所有行。

My Question is.. 我的问题是..

Shouldn't the while loop run at least once in the above case(without -r) and print the first line of output ? 在上述情况下,while循环是否应该至少运行一次(不带-r)并输出输出的第一行? Why the condition check fails on the first line itself ? 为什么条件检查在第一行本身失败?

Since all newlines are escaped, and read reads till an unescaped newline, it reaches end-of-file without getting one. 由于所有换行符均已转义,并且read读取直到未转义的换行符,因此到达文件末尾而没有得到换行符。 And, as help read says: 并且,如help read

Exit Status:
The return code is zero, unless end-of-file is encountered, read times out
(in which case it's greater than 128), a variable assignment error occurs,
or an invalid file descriptor is supplied as the argument to -u.

Note that line still contains the lines read so far: 请注意,该line仍包含到目前为止读取的行:

$ while read line; do echo "$line"; done < foo; echo $line
dog cat apple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM