Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Shell script launching Rake doesn't run correctly when launched via cron

I've written a Rake script that should run automatically with Crontab. The script runs fine when typed in the command line but fails to run correctly inside the cron.

The script looks like this :

#!/bin/sh

echo `date`
cd /home/mick/myapp/current
rake RAILS_ENV=production mynamespace:myaction

The crontab setting looks like this :

10 0,6,12,18 * * * /home/mick/work/launch.sh >> /home/mick/work/launch.log

After execution, the log file just contains the date but nothing else, and the error I get in the syslog looks like this :

Mar 18 18:10:01 CRON[21773]: (mick) CMD (/home/mick/work/launch.sh >> /home/mick/work/launch.log)
Mar 18 18:10:01 CRON[21772]: (CRON) error (grandchild #21773 failed with exit status 127)
Mar 18 18:10:01 postfix/sendmail[21776]: fatal: open /etc/postfix/main.cf: No such file or directory
Mar 18 18:10:01 CRON[21772]: (mick) MAIL (mailed 1 byte of output; but got status 0x004b, #012)

EDIT :

Thanks to @Holger Just's comment, i've found this link which helped me got a working script.

Here is the updated version of my script

#!/usr/bin/env bash # UPDATED TO GET ACCESS TO 'source'

export PATH=blabla # NOT SURE THIS HELPED AS IT WAS MY FIRST MODIF AND DIDN'T FIX
source /home/mick/.rvm/environments/default # LOADING RVM TO MAKE THINGS WORK
echo `date`
cd /home/mick/myapp/current
rake RAILS_ENV=production mynamespace:myaction
like image 212
Dirty Henry Avatar asked Oct 09 '22 09:10

Dirty Henry


1 Answers

Cron typically has a very restricted $PATH. So you could either set the $PATH on top of your script or use full paths throughout. You can set the path in your script like

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

Of course you probably need to adapt your $PATH. e.g. you could use that of your root user's login shell. You can get that by running echo $PATH.

Also note that if you use RVM, you need to load it in your cron script explicitly as cron doesn't load rvm (or any other shell initialization scripts) by default.

like image 52
Holger Just Avatar answered Oct 11 '22 01:10

Holger Just