Redirecting the output of a cron job

2020-02-21 08:23发布

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?

3条回答
▲ chillily
2楼-- · 2020-02-21 08:51

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

查看更多
太酷不给撩
3楼-- · 2020-02-21 09:04

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'
查看更多
够拽才男人
4楼-- · 2020-02-21 09:06

Judging by this answer you just need to switch the order of the redirects:

0 5 * * * /bin/bash -l -c 'export RAILS_ENV=my_env; cd /my_folder; ./script/my_script.rb > ./log/my_log.log 2>&1'
查看更多
登录 后发表回答