How to Configure Cron Script with Rake on DreamHost Shared Hosting

Setting up a cron script to use rake on DreamHost is fairly tricky.

Most cron implementations run the command under a limited environment compared to your usual log in. Every time my cron script was supposed to run, I would get a happy little email stating,

Could not find rake-10.1.0 in any of the sources

The eventual solution I discovered is to make sure you set the $PATH, $GEM_HOME, and/or $GEM_PATH environment variables in the script.

You should probably also make sure you use full paths to commands.

I wound up with this:

cron-script.sh
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
export RAILS_ENV=production
export PATH=/home/[USERNAME]/usr/local/bin:/opt/local/bin:/opt/local/sbin:/home/[USERNAME]/bin/:/home/[USERNAME]/.gems/bin:/usr/lib/ruby/gems/1.8/bin/:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games
export GEM_HOME=/home/[USERNAME]/.gems
export GEM_PATH=/home/[USERNAME]/.gems:/usr/lib/ruby/gems/1.8
cd /home/[USERNAME]/[PROJECT_FOLDER]
BUNDLE=/usr/lib/ruby/gems/1.8/bin/bundle
RAKE=/home/[USERNAME]/.gems/bin/rake
$BUNDLE exec $RAKE my_task

You can get the environment variable values by running the env command in your SSH terminal. Use the which bundle and which rake commands to get the full paths to the bundle and rake binaries.

With a little more experimenting, you might be able to pare down some of that extraneous setup.