2013-08-07 87 views
3

我有一個大的bash腳本,我想全局重定向所有標準輸出/標準錯誤到一個文件,一些進度指示器,如特定的回聲消息。例如,考慮下面的腳本Bash腳本全局重定向與執行和寫入屏幕

#!/bin/bash 

# all stdout and stderr go to out.log 
exec &> out.log 

special_echo "starting" 

# many other commands go here 
# which output both the stdout and stderr 
# also some special_echo commands in here, 
# for example 
echo "msg1" 
special_echo "middle" 
echo "msg2" >&2 

special_echo "finished" 

當它運行的輸出應

$ ./script 
starting 
middle 
finished 
$ 

但是,out.log應該包含

msg1 
msg2 

如何實現special_echo功能?我已經嘗試過使用文件描述符並回應,但無法將其顯示在屏幕上。

有沒有一種方法可以實現這一點,而無需爲每條線添加重定向或執行類似answer之類的操作?

回答

6

是,使用另一個文件描述符是要走的路:

#!/bin/bash 

exec 3>&1 
special_echo() { 
    echo "[email protected]" >&3 
} 

exec &> out.log 

special_echo "starting" 
echo "msg1" 
special_echo "middle" 
echo "msg2" >&2 
special_echo "finished" 
+0

完美地工作。我有'exec&> out.log',然後'exec 3>&1',現在我看到的是錯誤的順序。 – user2660278

0

重定向到/ dev/tty的,這是控制終端。也適用於輸入。

+0

重定向到/ dev/tty是否是POSIX? – smarber