为什么进程替换并不总是与在bash while循环工作?

问题描述:

借助进程替换与文件名精细的作品,例如无论

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

$ cat <FILENAME

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

工作

但如果不是filename,我们使用回声命令(或任何其他产生输出到标准输出),继续工作。

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 read i; do echo $i; done <(echo XXX) 
bash: syntax error near unexpected token `<(echo XXX)'

产生错误。

任何想法,为什么?

注意: &LT; 文件名是的的进程替换。这是一个重定向。进程替换的格式 &LT;(命令

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

进程替换替换的过程的为&LT的的名称;(...)。尽管采用的&LT; 骨节病>符号,它不是一个重定向

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

所以,当你说猫≤(回声富)时,bash创建一个子进程来运行回声命令,并代可以读取以获得该命令的输出的伪文件的名称。替代的结果将是这样的:

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

请注意没有一个重定向。 (您可以通过键入回声&LT看到这个动作;(回声富)

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

像许多实用工具,可以带或不带命令行参数来调用;如果未指定文件,那么它从标准输入读。因此,猫file.txt的猫&LT; 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.

,而命令不接受额外的参数。因此,

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

是一个语法错误。

is a syntax error.

进程替换不改变。因此,

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)

请注意必须有两个℃之间的空间; 骨节病>符号,以避免与这里-doc的语法混乱,&LT;&LT;字

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