如何将一个子shell的输出文件描述符重定向到父shell输入文件描述符? [英] How to redirect an output file descriptor of a subshell to an input file descriptor in the parent shell?

查看:528
本文介绍了如何将一个子shell的输出文件描述符重定向到父shell输入文件描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(在bash)我想子shell使用非STDOUT非STDERR的文件描述符传递一些数据返回给父shell。我该怎么办呢?最后,我希望将数据保存到父shell的一些变量。

(In BASH) I want a subshell to use a non-STDOUT non-STDERR file descriptor to pass some data back to the parent shell. How can I do that? Eventually I would love to save the data into some variable of the parent shell.

(
  # The following two lines show the behavior of the subshell.
  # We cannot change them.
  echo "This should go to STDOUT"
  echo "This is the data I want to pass to the parent shell" >&3
)
#...
data_from_subshell=... # Somehow assign the value of &3 of the
                       # subshell to this variable

编辑:
子shell运行黑箱程序写入到标准输出,并与功放; 3。

The subshell runs a black-box program that writes to STDOUT and &3.

推荐答案

当心,BASHISM AHEAD (有POSIX的炮弹是比bash的显著快,如灰或破折号,没有进程替换)。

BEWARE, BASHISM AHEAD (there are posix shells that are significantly faster than bash, e.g. ash or dash, that don't have process substitution).

您可以做一个手柄舞蹈原标准输出移动到一个新的描述符,以供管道标准输出(从我的头顶):

You can do a handle dance to move original standard output to a new descriptor to make standard output available for piping (from the top of my head):

exec 3>&1 # creates 3 as alias for 1
run_in_subshell() { # just shortcut for the two cases below
    echo "This goes to STDOUT" >&3
    echo "And this goes to THE OTHER FUNCTION"
}

现在你应该可以这样写:

Now you should be able to write:

while read line; do
    process $line
done < <(run_in_subshell)

≤()构造是一个bashism。你可以用管道替换它。

but the <() construct is a bashism. You can replace it with pipeline

run_in_subshell | while read line; do
    process $line
done

但比第二个命令的的中的子shell 的运行,因为所有的命令管道做。

except than the second command also runs in subshell, because all commands in pipeline do.

这篇关于如何将一个子shell的输出文件描述符重定向到父shell输入文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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