2015-07-10 172 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有什麼不一樣的? –