bash – 如何将subshel​​l的输出文件描述符重定向到父shell中的输入文件描述符?

(在BASH中)我想要一个subshel​​l使用非STDOUT非STDERR文件描述符将一些数据传回到父shell。我怎样才能做到这一点?最终我很想将数据保存到父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运行一个写入STDOUT和& 3的黑匣子程序。

BEWARE,BASHISM AHEAD(有posix shell比bash快得多,比如灰色或破折号,没有进程替换)。

您可以做一个句柄舞蹈将原始标准输出移动到一个新的描述符,使标准输出可用于管道(从我的头顶部):

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"
}

现在你应该可以写:

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

但是<()结构是一个bashism。您可以用管道替换它

run_in_subshell | while read line; do
    process $line
done

除了第二个命令也在subshel​​l中运行,因为管道中的所有命令都执行。

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...