2015-07-10 113 views
1

我有以下两个的bash脚本:bash的文件描述符重定向

one.bash:

#!/bin/bash 

echo "I don't control this line of output to stdout" 

echo "I don't control this line of output to stderr" >&2 

echo "I do control this line of output to fd 5" >&5 

callone.bash:

#!/bin/bash 

# here I try to merge stdout and stderr into stderr. 
# then direct fd5 into stdout. 

bash ./one.bash 1>&2 5>&1 

当我运行它像这样: bash callone.bash 2>stderr.txt >stdout.txt

stderr.txt文件如下所示:

I don't control this line of output to stdout 
I don't control this line of output to stderr 
I do control this line of output to fd 5 

并且stdout为空。

我想将“do control”行输出到只有stdout.txt。

上更改的限制有:

  1. 我可以改变callone.bash什么。
  2. 我可以更改我控制的one.bash中的行。
  3. 我可以在与文件描述符5相关的one.bash中添加一个exec。
  4. 我必须按照指示运行脚本。

[编辑]这样的用例是:我有一个脚本,可以执行其他脚本的各种运行,可以输出到stderr和stdout。但我需要确保用户只能看到控制良好的消息。因此,我将良好控制的消息发送到fd5,并将其他所有内容(stdout & stderr)发送到日志。

回答

7

重定向发生按顺序

一旦运行1>&2你更换FD 1 FD 2

所以,当你再运行5>&1要重定向FD 5到FD 1点现在(不是它在哪里的时候才开始) 。

您需要反转两个重定向:

bash ./one.bash 5>&1 1>&2 
+0

的有趣的事情是,当管道介入,这是*不*相同。 – o11c

+0

@ o11c,先设置管道,然后是重定向。请参阅http://stackoverflow.com/a/12027221/1524545 – geirha

+0

@ o11c有什么不一样的? –