检查bash脚本中是否有标准输出重定向 [英] Check if there is an stdout redirection in bash script

查看:60
本文介绍了检查bash脚本中是否有标准输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例:

$ 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 

推荐答案

您可以检查stdout是否为终端.当stdout重定向或通过管道传输时,它将不是终端.您可以将test命令与-t选项一起使用以获取以下信息:

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:

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

这篇关于检查bash脚本中是否有标准输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆