Cron Job: Run rails rake task in shell script

To run a rake task within a shell script using a cron job, do the following:

First, specify the shell at the top of your .sh script

#!/bin/sh

 
Then, change your directory to your rails application in your .sh script

cd /home/user/app/current

 
Now, you need to manually define your PATH within the script:

PATH=/your/paths:/etc/etc

 
To see your user’s PATH, do the following in your terminal: echo $PATH

Now, assign your rake executable path to a variable in your script:

RAKE_PATH=/home/user/.rvm/rubies/your-ruby/bin/rake

 
To see where the rake executable is located, do the following in your terminal: which rake

Finally, to execute your rake task, do the following:

RAILS_ENV=production $RAKE_PATH your_task

 
So, the final version of your .sh script would look something like this:

#!/bin/sh
cd /home/user/app/current
PATH=/your/paths:/etc/etc
RAKE_PATH=/home/user/.rvm/rubies/your-ruby/bin/rake
RAILS_ENV=production $RAKE_PATH your_task

Leave a Reply

Your email address will not be published. Required fields are marked *