Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

For example, I can log stderr of one script in this way:

* * * * * run_script.sh > /var/log.txt 2>&1

But I want to log stderr of all scripts in my crontab. I can append > /var/log.txt 2>&1 to all scripts, but it's not good if I have hundreds of scripts in cron. Is there another, more simple way to do this?

share|improve this question
add comment

2 Answers

 Any output produced by a command is sent to the user specified in the
 MAILTO environment variable as set in the crontab(5) file or, if no
 MAILTO variable is set (or if this is an at(1) or batch(1) job), to the
 job's owner.  If a command produces no output or if the MAILTO
 environment variable is set to the empty string, no mail will be sent.

Since it uses local mail, you really don't need to set up anything, or maybe just install mailx if it's not already here. Cron will send you the output, you can save the mail in a file and do many things from there. Trying to modify the way cron works to directly suit your need is not the way to go. If you don't think so, just patch and re-buil cron, call it my_cron and use it instead of cron. And be prepared to eventually keep your my_cron up to date and re-build it often.

Add this at the beginning of all your scripts to log everything and stop at the first error

exec 2>&1 > /var/log/YOUR_LOG_FILE
set -e
share|improve this answer
add comment

In crontab, you can set MAILTO to point to a mail alias that runs a script. That script would accept a mail message, strip off the headers and other goop, and log the remainder with logger. Since all cron script output is sent to the address specified by MAILTO, you'd capture everything.

Example: in crontab

MAILTO=myalias

In /etc/mail/aliases (assuming you're using sendmail)

myalias:"|/usr/local/bin/my-processing-script.sh"

and have the script strip off the mail headers and process the cron output.

share|improve this answer
    
can you be more specific about setting up the MAILTO, alias, MTA, script, etc? –  endolith Nov 29 '12 at 2:27
1  
@endolith I've edited the answer to give a basic setup which should work for sendmail and broadly compatible MTAs. You'll have to write the script yourself. –  Kyle Jones Nov 29 '12 at 3:05
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.