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:

if 'redirection is not empty'; then 
    cat <redirection name> | mailx -s "This is a test email." [email protected] 
fi 
3
  • I'm not sure I understand. If called as myprogram > something, you want to mail the content of something? Commented Nov 5, 2014 at 16:08
  • Can you please ask a question. Commented Nov 5, 2014 at 16:21
  • correct, I want keep someting and send it into body message Commented Nov 5, 2014 at 16:24

1 Answer 1

33

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
Sign up to request clarification or add additional context in comments.

9 Comments

@hek2mgl Well, on Linux, you might actually be able to, at least for redirections (not for pipes, though as there is no name), by looking at e.g. readlink /proc/$$/fd/1 or such...
@twalberg Yeah, you are right! Cool! Didn't had this in mind.. Thx! :)
Thanks twalberg, could you explain me how can manage this file (I tryed to copy/cat/type but everytime I receive an error)?
@hek2mgl, cannot agree regarding "good program design", it depends. Say such fundamental utils as /bin/ls /usr/bin/diff. (1) ls gives tabular output to terminal, but gives one per line when output is redirected. (2) diff may use color output with ANSI escape codes, but does pure black-n-white output by default when redirected. So there are cases when good program design demands to know whether stdout is a terminal
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.