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

前端之家收集整理的这篇文章主要介绍了bash – 如何将subshel​​l的输出文件描述符重定向到父shell中的输入文件描述符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
(在BASH中)我想要一个subshel​​l使用非STDOUT非STDERR文件描述符将一些数据传回到父shell。我怎样才能做到这一点?最终我很想将数据保存到父shell的某个变量中。
  1. (
  2. # The following two lines show the behavior of the subshell.
  3. # We cannot change them.
  4. echo "This should go to STDOUT"
  5. echo "This is the data I want to pass to the parent shell" >&3
  6. )
  7. #...
  8. data_from_subshell=... # Somehow assign the value of &3 of the
  9. # subshell to this variable

编辑:
子shell运行一个写入STDOUT和& 3的黑匣子程序。

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

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

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

现在你应该可以写:

  1. while read line; do
  2. process $line
  3. done < <(run_in_subshell)

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

  1. run_in_subshell | while read line; do
  2. process $line
  3. done

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

猜你在找的Bash相关文章