Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save cronjob error to file and email it?

Tags:

linux

cron

my goal is to save cronjob error and email it to me. I don't care about standard output, that's why I redirect it to /dev/null.

Sending mail is done by this setting in crontab:

[email protected]

I tried to run it with following command:

* * * * * /path/to/script.sh > /dev/null 2 >> /path/to/file.log

It emails the error all right. The log file is created but is empty.

What am I doing wrong?

==================================================================================

I found the solution. Thank you all for your help! (I cannot post it as an answer, so I am amending the solution here.)

I used this reference How can I redirect stderr to a pipe?

# version 2: redirect stderr to the pipe without getting stdout (it's
# redirected to /dev/null)
myprog 2>&1 >/dev/null | grep ...

My solution is:

#crontab    
[email protected]
* * * * * /path/to/script.sh 2>&1 >/dev/null | tee -a /path/to/file.log

Explanation: redirecting stderr to the pipe without getting stdout and then using tee -a for appending the stderr to the log file and printing it to the terminal, which is redirected automatically to email (see MAILTO).

So I have a log file and email both containing the error message.

like image 804
Petr Avatar asked Sep 04 '25 17:09

Petr


1 Answers

My solution is:

#crontab    
[email protected]
* * * * * /path/to/script.sh 2>&1 >/dev/null | tee -a /path/to/file.log

Explanation see above in my first post.

like image 145
Petr Avatar answered Sep 07 '25 12:09

Petr