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在脚本中检测到重定向。这可能吗?

4

1 回答 1

5

您可以使用-tbash 的选项:

 -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
于 2013-04-16T09:26:05.523 回答