2013-04-16 114 views
2

我有一個bash腳本,如果輸出顯示在終端中,或者它被重定向到文件,它必須以不同的方式運行。它必須這樣做(myscript.sh):檢查腳本是否被重定向

if [ redirected_to_terminal ] ; then 
    flag="--color" 
else 
    flag="--no-color" 
fi 

grunt $flag 

這被稱爲是這樣的:

./myscript.sh 

或者這樣:

./myscript.sh > /tmp/log.txt 

stdout重定向將檢測在腳本中。這可能嗎?

回答

5

您可以使用-t選項的bash:

-t fd True if file descriptor fd is open and refers to a terminal. 

並檢查這樣的:

if [[ -t 1 ]]; then 
# console is attached 
else 
# Redirected to somewhere 
fi 
+0

+1 .. OP,你也不妨檢查標準錯誤。 – anishsane

相關問題