How to set PATH variable in crontab via whenever gem

2.1k Views Asked by At

Is it possible to set the PATH or SHELL variable in a crontab via the whenever schedule.rb file?

# here I want to set the PATH and SHELL variable somehow

every 3.hours do
  # some cronjob
end

I want this output in my crontab after my capistrano deploy:

SHELL=/bin/bash
PATH=/usr/local/bin:/usr/local/sbin:/sbin:/usr/sbin:/bin:/usr/bin:/usr/bin/X11
# some cronjobs
2

There are 2 best solutions below

1
On BEST ANSWER

Ok, it seems as I found the solution. I found it here: https://gist.github.com/jjb/950975

I will update this answer when I have tested it

I have to put this into my schedule.rb

# If your ruby binary isn't in a standard place (for example if it's in /usr/local/bin,
# because you installed it yourself from source, or from a thid-party package like REE),
# this tells whenever (or really, the rails runner) where to find it.
env :PATH, '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin'
4
On

You are already doing it when running zenity when setting DISPLAY, LANG etc.

If you want to set the shell, set it in the first line of /home/username/script/script1.sh using #!/bin/bash.

If you want to set the path, one way to do it is to set it before running the command:

5    9-20 * * * PATH=/usr/local/bin:/usr/local/sbin:/sbin:/usr/sbin:/bin:/usr/bin:/usr/bin/X11 /home/username/script/script1.sh > /dev/null

A alternate/better way is to create a simple wrapper script like so:

#!/bin/bash
export PATH=/usr/local/bin:/usr/local/sbin:/sbin:/usr/sbin:/bin:/usr/bin:/usr/bin/X11

# Absolute path to this script
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
SCRIPTPATH=`dirname $SCRIPT`

#make sure we are in the same directory as the script1.sh - this is useful in case the script assumes it is running from the same directory it's in and makes relative directory/file references
cd $SCRIPTPATH



##run final script, and pass through all parameters that were passed to wrapper script.
/home/username/script/script1.sh "$@"