为什么进程替换并不总是与 bash 中的 while 循环一起使用? [英] why process substitution does not always work with while loop in bash?

查看:12
本文介绍了为什么进程替换并不总是与 bash 中的 while 循环一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进程替换适用于文件名,例如两者

The process substitution works with filenames fine, e.g. both

$ cat <FILENAME

$ while read i; do echo $i; done <FILENAME

工作.

但是如果我们使用 echo 命令(或任何其他生成输出到标准输出的命令)代替 FILENAME,cat 继续工作

But if instead of FILENAME we use echo command (or any other, which generates output to stdout), cat continues to work

$ cat <(echo XXX)
XXX

while 循环

$ while read i; do echo $i; done <(echo XXX) 
bash: syntax error near unexpected token `<(echo XXX)'

产生错误.

知道为什么吗?

推荐答案

注意: <filename不是进程替换.这是一个重定向.进程替换的格式为 <(command).

Note: <filename is not process substitution. It's a redirection. Process substitution has the format <(command).

进程替换用进程名称代替<(...).尽管使用了 < 符号,但它不是重定向.

Process substitution substitutes the name of a process for the <(...). Despite the use of the < symbol, it is not a redirect.

所以当你说 cat <(echo foo) 时,bash 创建一个子进程来运行 echo 命令,并替换一个伪文件的名称,它可以被读取以获取该命令的输出.替换的结果将是这样的:

So when you say cat <(echo foo), bash creates a subprocess to run the echo command, and substitutes the name of a pseudo-file which can be read to get the output of that command. The result of the substitution will be something like this:

cat /dev/fd/63

注意没有重定向.(您可以通过键入 echo <(echo foo) 来查看此操作.)

Note the absence of a redirect. (You can see this in action by typing echo <(echo foo).)

像许多实用程序一样,cat 可以使用或不使用命令行参数来调用;如果未指定文件,则从 stdin 读取.所以 cat file.txtcat <file.txt 非常相似.

Like many utilities, cat can be invoked with or without a command-line argument; if no file is specified, then it reads from stdin. So cat file.txt and cat < file.txt are very similar.

但是 while 命令不接受额外的参数.所以

But the while command does not accept additional arguments. So

while read -r line; do echo "$line"; done < file.txt 

有效,但是

while read -r line; do echo "$line"; done file.txt

是语法错误.

过程替换不会改变这一点.所以

Process substitution doesn't change that. So

while read -r line; do echo "$line"; done /dev/fd/63

是一个语法错误,因此也是

is a syntax error, and consequently so is

while read -r line; do echo "$line"; done <(echo foo)

要从进程替换中指定重定向,您需要一个重定向:

To specify the redirect from the process substitution, you need a redirect:

while read -r line; do echo "$line"; done < <(echo foo)

请注意,两个 < 符号之间必须有一个空格,以避免与here-doc"语法 <<word 混淆.

Note that there must be a space between the two < symbols to avoid confusion with the "here-doc" syntax, <<word.

这篇关于为什么进程替换并不总是与 bash 中的 while 循环一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆