简体   繁体   中英

Check if there is an stdout redirection in bash script

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 :

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

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

From man test :

  -t FD file descriptor FD is opened on a terminal 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM