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

时间:2021-07-07 00:15:29

I need to check if my program's output is being redirected; if yes I need to keep and send its by mail.

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

example:

例:

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

myprogram.sh:

myprogram.sh:

if 'redirection is not empty'; then 
    cat <redirection name> | mailx -s "This is a test email." polly@gmail.com 
fi 

1 个解决方案

#1


9  

You can check if stdout is a terminal. When stdout is redirected or piped it will not be a terminal. You can use the test command with the -t option to get this information:

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

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

From man test:

从男人测试:

  -t FD  file descriptor FD is opened on a terminal

#1


9  

You can check if stdout is a terminal. When stdout is redirected or piped it will not be a terminal. You can use the test command with the -t option to get this information:

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

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

From man test:

从男人测试:

  -t FD  file descriptor FD is opened on a terminal