Check if there is a stdout redirection in bash script

I need to check if the output of my program is redirected; if so, I need to save and mail it.

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 
+5
source share
1 answer

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 
+6
source

Source: https://habr.com/ru/post/1206258/


All Articles