将进程的管道输出到 sh while 循环? [英] piping output of process to sh while loop?

查看:61
本文介绍了将进程的管道输出到 sh while 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 while 循环中逐行循环遍历 Perl 进程的输出.但是,我在语法上遇到了困难.

I'm trying to loop over the output of a Perl process, line by line, within a while loop. However, I'm having difficulty with the syntax.

我试过这个,但得到一个不明确的重定向"错误:

I tried this, but got an "ambiguous redirect" error:

#!/bin/sh

while read line; do 
    echo "$line" 
    # do stuff with $line 
done < $(perl process.pl)

./script.sh : line 6: $(perl process.pl): ambiguous redirect

例如,一种(低效的)解决方案是:

For instance, one (inefficient) solution would be:

#!/bin/sh

tmpFile=/tmp/tmpFile.txt
perl process.pl > $tmpFile 
while read line; do 
    echo "$line" 
    # do stuff with $line 
done < $tmpFile

我知道我可以将 Perl 进程通过管道传输到 while 循环中:

I know I can pipe the Perl process to a while loop as:

perl process.pl | while ...

但是 while 循环是在子 shell 中执行的,我需要在 while 循环中设置一些变量以在循环完成后保留,所以这不是一个选项.

but the while loop is executed in a subshell, and I need some variables set in the while loop to remain after the loop finished, so this is not an option.

我能做什么?

推荐答案

大功告成.试试这个:

while read -r line; do 
    echo "$line" 
    # do stuff with $line 
done < <(perl process.pl)

唯一的区别是 < 而不是 $.

The only difference is the < instead of the $.

$(cmd) 是一个命令替换,它扩展到括号​​内的命令的输出.另一方面,<(cmd)进程替换.请注意,这是一个 Bash 扩展,因此如果要使用此方法,还应该将 shebang 更改为 #!/bin/bash.

$(cmd) is a command substitution, which expands to the output of the command within the parentheses. On the other hand, <(cmd) is a process substitution. Note that this is a Bash extension, so you should also change your shebang to be #!/bin/bash if you want to use this method.

或者,如果您不使用 Bash,您可以简单地使用管道代替:

Alternatively, if you are not using Bash, you can simply use a pipe instead:

perl process.pl | while read -r line; do 
    echo "$line" 
    # do stuff with $line 
done

顺便说一句,你几乎总是想使用 -r 与读取切换

As an aside, you almost always want to use the -r switch with read

这篇关于将进程的管道输出到 sh while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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