Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How can I run another command if there is any input on the standard input

commonly used in situations like this:

some command with no normal output | ifinput mail -s 'some output' me

share|improve this question
add comment

3 Answers 3

up vote 2 down vote accepted

The simplest solution would be using a file (if you dare!). The -s switch means "file is not zero size". The &> redirections includes errors as well (means that stdout and stderr will be sent).

OUTFILE=/tmp/command.out
some command &> $OUTFILE
[ -s "$OUTFILE" ] && mail -s "subject here" email@example.com < "$OUTFILE"

Edit: the comment below by glenn jackman contains even a better solution.

share|improve this answer
2  
Don't really need a file for that: output=$(some command); [[ -n "$output" ]] && mail ... <<< "$output" –  glenn jackman Jul 15 '11 at 17:33
add comment

A little trickery with read:

$ echo 1 | { read -t 0 -N 0 && cat ; } 
1
$ { read -t 0 -N 0 && cat ; } 
$ 
share|improve this answer
    
Hmm looks promising - can you show an example sending "1" to the mail command? In your example, would I just replace cat with the command that I wanted to run? –  ckliborn Jul 15 '11 at 15:11
    
That's correct. –  Ignacio Vazquez-Abrams Jul 15 '11 at 15:13
add comment

You could also create a shell script. That script could first call some command that redirects the output to a file and then call the mail command from within the script to send it out which is essentially what SamKrieg is doing without the need to create a shell script. A reason for the script may depend on if you want to run this command as a cron job or somehting.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.