开发者

How do I redirect both stderr and stout to multiple locations?

I need to execute a command in a bash script (on freebsd6), and I need to have both the stderr and stdout of the command sent to the console, a log file, AND to a bash variable.

So, without any redirection, what I want is:

result=`./command | tee output.log`

If I run this as-is, only stderr makes it to the console, and only stdout makes it to both the output.log file and the $result variable. I understand why that is, but many attempts at different redirections have failed to send both streams to all three locations.

How do I send both stderr and stdout to all three loc开发者_StackOverflowations?


result=`./command 2>&1 | tee output.log | tee /dev/tty`

[edit]

As n.m. points out in a comment, tee accepts multiple arguments:

result=`./command 2>&1 | tee output.log /dev/tty`

[second edit]

Borrowing an idea from Chris in the comments, you can also do this to send the output to stderr:

result=`./command 2>&1 | tee /tmp/foo.log >(cat 1>&2)`

To do exactly what you want, the best I have found is this:

exec 3>&1 ; result=`./command 2>&1 | tee /tmp/foo.log >(cat 1>&3)` ; exec 1>&3

(The whole problem here is that the backticks redirect stdout before anything inside gets to execute. So this line saves and restores the old stdout as descriptor 3, which may or may not be a good idea...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜