ky4k0b
ky4k0b

Reputation: 147

How to send mail depending on stdout?

I need to send emails only when I have anything in stdout. Right now I send mails every 10 minutes configured in cron like this, even if the script returns nothing:

/root/script.sh|mail -s topic [email protected]

How can I skip sending mails on null stdout?

Upvotes: 1

Views: 2559

Answers (2)

Tony Stark
Tony Stark

Reputation: 2468

I found even a better solution. Use the -E option for the mail command and it won't send e-mails if the body is empty. The manual for mail states the following.

-E      Do not send messages with an empty body.  This is useful for 
piping errors from cron(8) scripts.

So just like that.

/root/script.sh|mail -E -s topic [email protected]

Upvotes: 7

clt60
clt60

Reputation: 63892

You can try:

message=$(/root/script.sh) && [[ ! -z "$message" ]] && mail -s topic [email protected]  <<< "$message"

Meaning:

  • store the output from the script.sh to an variable
  • if the script.sh exits without error (exit status 0)
  • check the content of the variable message
  • and if it isn't empty
  • send email

Upvotes: 2

Related Questions