Bash while 循环逐行读取文件
我想在这里讨论两种逐行读取文件的方法:
#!/bin/bash
while read line
do
echo-e "$ line \ n"
done <file.txt
所以
#!/bin/bash
exec 3<file.txt
while read line
do
echo-e "$ line \ n"
done
第一个版本工作正常,但我不明白 while 循环处理文件的机制。但第二个版本的机制我了解。但在这里我不明白为什么它挂起并且不打印任何内容。
There are two ways of reading a file line by line that I want to discuss here:
#!/bin/bash
while read line
do
echo-e "$ line \ n"
done <file.txt
and
#!/bin/bash
exec 3<file.txt
while read line
do
echo-e "$ line \ n"
done
So first version works fine but I don't understand the mechanism of working while loop with the file. But the mechanism of the second version I understand. But here I don't understand why it hangs and does not print anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个循环之所以有效,是因为
done
之后的重定向适用于整个循环,因此read
是从文件读取,而不是从脚本的标准输入读取。第二个版本挂起是因为
read
从文件描述符 0(标准输入)读取,而您没有在其中键入任何内容。exec
行重定向文件描述符 3 以从文件中读取,但您不是从文件描述符 3 读取。您可以使用以下方法来挽救第二个:
现在从指定文件读取标准输入。
The first loop works because the redirection after the
done
applies to the whole loop, so theread
there is reading from the file, not from the standard input of the script.The second version hangs because
read
reads from file descriptor 0, which is standard input, and you've not typed anything there. Theexec
line redirects file descriptor 3 for reading from the file, but you're not reading from file descriptor 3.You could rescue the second by using:
Now standard input is read from the named file.
这可能对您有用:
-u3
从文件描述符 3 读取奇怪的是
echo
没有像 ksh 的print
命令那样的补码开关。This might work for you:
-u3
reads from file descriptor 3Strange that
echo
does not have the complement switch like ksh'sprint
command.您的脚本中几乎没有错误。
$
和变量名之间有空格。 (可能是错误的编辑)echo
和-e
之间有空格。 (可能是错误的编辑)它应该是这样的 -
There are few mistakes in your scripts.
$
and variable name. (may be bad edit)echo
and-e
. (may be bad edit)It should be something like this -
-u3 非常适合我的目的(仅阅读以下行)
-u3 is great for my purpose (reading only the following line)