2013-07-25 36 views
0

如何將腳本的stdout和stderr重定向到文件,同時將腳本的stderr發送到標準輸出。非標準io重定向

舉例說明:

testscript:

#!/bin/bash 
echo "this goes to stdout" 
echo "this goes to stderr" >&2 

以這樣的方式執行testscript它打印此控制檯:

this goes to stderr 

,這轉到日誌文件:

this goes to stdout 
this goes to stderr 

我覺得我近距離使用fifo,但從未到過那裏。需要的是stderr的tee。想法?

回答

0

我想這是不是對答案的工作,現在的人真是公平的,但我想我明白了:

if [ ! -e /tmp/deployed.err ] 
then 
    mkfifo /tmp/deployed.err 
fi 

tee -a testlog </tmp/deployed.err & 

./testscript 2>/tmp/deployed.err 1>>testlog 

這似乎是工作,但我擔心的是,在消息日誌將失去秩序。任何人有更好的主意?

0

command 2>&1 | tee somefile 

都將標準錯誤和標準輸出發送到tee所以,既要文件和標準輸出了。

如果你想stderr和stdout重定向到不同tee,您可以使用類似:

command > >(tee out.log) 2> >(tee err.log >&2) 

等等...(> >(之間的空間是必須的)

0

你可以試試像這樣

./script 2>&1 1>log | tee -a log 

的標準輸出發送到登錄1>log和T做的將它發送到標準輸出和日誌的工作。 PS:不知何故,我對這種方法有不好的感覺。如果你有這種感覺,請評論。

0

simething simplier。這是基於bashizm內部叉 首先,測試腳本:

#!/bin/bash 
for i in {1..1000}; do 
    echo STDOUT $i>&1 
    echo STDERR $i>&2 
done 

和明年,重定向腳本:

(./xxtext.sh 1>>logfile)2>&1|\ #subprocess/fork in brackets with redir stdout to logfile. 
#above, main process redirect stderr to stdout for properly pipe 
while read x; do echo $x; echo $x>>logfile; done #second read sequently stdin 
#redirected from stderr, and both print to the screen and append to logfile. 

可惜,這不是救正確順序,因爲兩個流是由兩種不同的工藝管理用管道緩衝他們。

如果您確實想要保存序列,則只能使用'select'系統調用並從內部打開的腳本中讀取stdout和stderr。我相信bash不支持這一點。 您可以在C或Perl或其他更高級的lang中執行此操作。 在perl中的有用示例我發現在:http://www.perlmonks.org/bare/?node_id=419919 這稱爲'bc'命令。