2013-04-16 76 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

相关问题