如何在 bash 中重定向嵌套函数调用的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3769552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I redirect output of nested function calls in bash?
提问by zarzar
I have a bash script that has a few functions which are all called within 1 function. How can I pipe all the output from all the functions up to the main one? I'll be using tee as well to display that output to term and to a log file.
我有一个 bash 脚本,其中有几个函数都在 1 个函数中调用。如何将所有功能的所有输出通过管道传输到主要功能?我还将使用 tee 将输出显示到术语和日志文件中。
func 1
func 2
func 3
func 1
func 4
func 2
func 3
call func 4 # i want to grab it here
回答by DigitalRoss
Hmm, when in doubt, use ( )which will run a subshell and redirect its entire output.
嗯,如有疑问,请使用( )which 将运行子shell并重定向其整个输出。
So, try something like:
因此,请尝试以下操作:
( mytoplevelfunc ) | tee whatever
回答by Paused until further notice.
As DigitalRoss said, all stdout goes to the same place and piping and teeing works regardless of how deeply functions and scripts are nested (up to system limits). In the demo below, function f4demonstrates one way of doing it and f5demonstrates another.
正如 DigitalRoss 所说,无论函数和脚本嵌套多深(达到系统限制),所有标准输出都将到达同一个地方,并且管道和 Teeing 都可以工作。在下面的演示中,函数f4演示了一种方法并f5演示了另一种方法。
$ f1 () { echo f1; }
$ f2 () { echo f2; }
$ f3 () { echo f3; f1; }
$ f4 () { echo f4; f2; f3; }
$ f4
f4
f2
f3
f1
$ f4 | tee tee.out
f4
f2
f3
f1
$ cat tee.out
f4
f2
f3
f1
$ f5 () { { echo f4; f2; f3; } | tee tee2.out; }
$ f4 | tee tee.out
f4
f2
f3
f1
$ cat tee.out
f4
f2
f3
f1
回答by kapetr
$ { echo aaaa; echo bbbb >/tmp/x; echo cccc; } >/tmp/y
$ cat x
bbbb
$ cat y
aaaa
cccc
even real nested redirection works
(not just with (), but even with {})
即使是真正的嵌套重定向也能工作
(不仅使用(),甚至使用{})

