2014-11-05 82 views
5

我需要檢查我的程序輸出是否被重定向;如果是的話,我需要保留並通過郵件發送。檢查bash腳本中是否存在stdout重定向

例如:

$ myprogram -param1 -param2 -param3 > /home/polly/log.txt 

myprogram.sh

if 'redirection is not empty'; then 
    cat <redirection name> | mailx -s "This is a test email." [email protected] 
fi 
+0

我不知道我的理解。如果被稱爲'myprogram> something',你想郵寄'something'的內容? – 2014-11-05 16:08:19

+0

你可以問一個問題。 – Steffen 2014-11-05 16:21:12

+0

正確,我想保持someting併發送到正文消息 – JackFrost65 2014-11-05 16:24:32

回答

6

您可以檢查是否stdout是終端。當stdout被重定向或傳送時,它不會是一個終端。您可以使用測試命令與-t選項得到這個信息:

if [ -t 1 ] ; then 
    # stdout is a terminal 
else 
    # stdout isn't a terminal 
fi 

man test

-t FD file descriptor FD is opened on a terminal 
+0

好吧,但我在哪裏可以找到標準輸出的名稱? – JackFrost65 2014-11-05 16:30:22

+0

您無法獲取文件名(或管道後面的命令) – hek2mgl 2014-11-05 16:50:40

+1

[參考](http://stackoverflow.com/questions/5602663/how-to-get-the-name-of-a-file-acting-as -stdin-stdout) – kojiro 2014-11-05 18:43:26