Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting the output of a cron job

I have the following entry in crontab:

0 5 * * * /bin/bash -l -c 'export RAILS_ENV=my_env; cd /my_folder; ./script/my_script.rb 2>&1 > ./log/my_log.log'

The result of this is that I am receiving the output of ./script/my_script.rb in ./log/my_log.log. This behavior is desired. What is curious is that I am also receiving the output in my local mail. I am wondering how the output of my script is being captured by mail. Since I am redirecting the output to a log file, I would expect that my cron job would have no output, and thus I would receive no mail when the cron job runs. Can anyone shed some light as to how mail is able to get the output of ./script/my_script.rb?

like image 649
Michael Frederick Avatar asked Feb 20 '13 15:02

Michael Frederick


People also ask

How do I redirect the output of a cron job?

In your /etc/cron. d/example1 config file, the command must use /bin/sh syntax. Specifically any shell redirection must be /bin/sh syntax. If you try to use for example csh shell redirect syntax in your /etc/cron.

Where does output from cron jobs go?

Like most daemons running on our system, the cron daemon logs its output somewhere under /var/log.

How do I change the path of crontab?

Run crontab and grab $PATH value used by crontab. Now edit crontab again to set your desired java bin path: a) crontab -e ; b) PATH=<value of $JAVA_HOME>/bin:/usr/bin:/bin (its a sample path); c) now your scheduled job/script like */10 * * * * sh runMyJob.sh & ; d) remove echo $PATH from crontab as its not needed now.

What is the use of * * * * * In cron?

It is a wildcard for every part of the cron schedule expression. So * * * * * means every minute of every hour of every day of every month and every day of the week .


2 Answers

Your redirection order is incorrect. Stderr is not being redirected to the file, but is being sent to stdout. That's what you must be receiving in your mail.

Fix the redirection by changing your cron job to:

0 5 * * * /bin/bash -l -c
'export RAILS_ENV=my_env;
cd /my_folder;
./script/my_script.rb > ./log/my_log.log 2>&1'
like image 189
dogbane Avatar answered Oct 09 '22 20:10

dogbane


Try swapping 2>&1 with > ./log/my_log.log.

like image 21
Ilya I Avatar answered Oct 09 '22 18:10

Ilya I