BASH shell wrapper script to setup RVM environment and execute Ruby scripts via cron
Here’s a BASH shell wrapper script I use to execute Ruby scripts via cron. It ensures the following are setup correctly: environment variables, Ruby version, RVM gemset, and will pass command line arguments to Ruby. It assumes an .rvmrc file exists in the same directory as the script being executed.
#!/usr/bin/env bash
# check if rvm_path var is empty and should be sourced
if [ "x$rvm_path" = "x" ]; then
source $HOME/.bashrc
fi
# load rvm
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
source "/usr/local/rvm/scripts/rvm"
else
printf "ERROR: An RVM installation was not found.\n"
exit
fi
# enter script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $SCRIPT_DIR
# source .rvmrc file
source .rvmrc
# get script name
SCRIPT_NAME=`basename $0`
# replace ".sh" with ".rb"
RUBY_SCRIPT=`echo ${SCRIPT_NAME} | sed 's/\.sh$/\.rb/'`
# construct command line with arguments
COMMAND="./${RUBY_SCRIPT} ${@}"
# execute
$COMMAND
Usage:
# make both files executable (chmod +x script.sh script.rb)
/my/path/script.sh
/my/path/script.rb
Cron entry added to /etc/crontab:
SHELL=/bin/bash
# NOTE: $PATH copied from operational user shell
PATH=/usr/local/rvm/gems/ruby-2.0.0-p247@MYGEMSET/bin:/usr/local/rvm/gems/ruby-2.0.0-p247@global/bin:/usr/local/rvm/rubies/ruby-2.0.0-p247/bin:/usr/local/rvm/bin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/rvm/bin
MAILTO=root
HOME=/root
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
0 * * * * root /my/path/script.sh --sample args