1

I have a process which is started by Сron like this:

timeout 1h /app/longprocess.sh

Now I want to be notified by email if something goes wrong with it. Imagine this:

notifyme maintainer@example.org timeout 1h /app/longprocess.sh

where notifyme is a supposed command which will send an email to maintainer@example.org with the output of the command in case the command exits with a non-zero status. Is there something like this?

Igor Mukhin
  • 231
  • 1
  • 2
  • 5

3 Answers3

2

cron already sends mails, if a compatible /usr/sbin/sendmail is installed (e.g. msmtp, ssmtp, Postfix, OpenSMTPD…). See also: What is the "You have new mail" message in Linux/UNIX?

chronic from moreutils can handle the "only on success" part:

chronic timeout 1h /app/longprocess.sh
u1686_grawity
  • 452,512
2
sometask||echo Something Went Wrong! | mail -s E-MailSubject user@example.com

The || will only run what is on the right, if the command on the left returns a non-zero error code. This functionality is built into the shell (I'm seeing this question has the "bash" tag), so no extra external program is needed to support that functionality. The "mail" program is quite commonly pre-installed on many operating systems.

Similarly, you could do:

sometask&&echo Something Went Right! | mail -s E-MailSubject user@example.com

which would only run what happened on the right if things were successful. (By "successful", I specifically mean that "zero" is the return code from the command specified on the left.)

Edits: I initially wrote this late at night and, unfortunately, an update was required for accuracy, which is why comments pointed out some aspects of the answer. (Thanks MariusMatutiae and grawity!) I decided that, in the long term, fixing the answer is better than leaving it in a state that is more prone to cause confusion.

TOOGAM
  • 15,798
  • 5
  • 43
  • 63
  • No, this is incorrect: actually, the code on the right of && will be run if and only if sometask does not report an error. What you should write, to achieve you describe, is sometask || cmd: cmd will be run iff sometask fails. – MariusMatutiae Nov 04 '15 at 13:44
  • It's true that sendmail is commonly preinstalled, however, it usually does not accept such options as -s <subject> – it expects a full RFC 822 message to be given. Perhaps you're confusing it with the mail command? – u1686_grawity Nov 04 '15 at 13:45
-2

You can always use the following method by adding:

MAILTO=xyz@example.com

in your cron and you will be inform. I have tried this and it worked for me all the time.

kenorb
  • 25,417