(在BASH中)我想要一个subshell使用非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
除了第二个命令也在subshell中运行,因为管道中的所有命令都执行。