检查bash脚本中是否有stdout重定向

时间:2014-11-05 16:02:48

标签: linux bash

我需要检查我的程序输出是否被重定向;如果是的话,我需要保留并通过邮件发送。

示例:

$ 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." polly@gmail.com 
fi 

1 个答案:

答案 0 :(得分:10)

您可以检查stdout是否是终端。当stdout被重定向或管道传输时,它将不是终端。您可以使用带有-t选项的test命令来获取此信息:

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