Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there is an stdout redirection in bash script

Tags:

linux

bash

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." [email protected] 
fi 
like image 508
JackFrost65 Avatar asked Nov 05 '14 16:11

JackFrost65


1 Answers

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
like image 59
hek2mgl Avatar answered Nov 07 '22 21:11

hek2mgl