Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#!/usr/bin/env ruby is not found in cron

Tags:

bash

ruby

cron

I have a simple ruby script, hello.rb:

#!/usr/bin/env ruby
puts 'hello' 

It runs ok at the command line:

# /usr/local/src/hello/hello.rb
hello

However, if I put it in cron:

* * * * * /usr/local/src/hello/hello.rb >> /usr/local/src/hello/hello.log 2>&1

There are errors in the log file:

/usr/bin/env: ruby: No such file or directory
/usr/bin/env: ruby: No such file or directory
...
/usr/bin/env: ruby: No such file or directory

/usr/bin/env ruby runs ok at command line though:

# /usr/bin/env ruby -v
ruby 1.8.7 (2012-10-12 patchlevel 371) [i686-linux]

How to fix the env error for cron?

like image 416
ohho Avatar asked Apr 12 '13 03:04

ohho


2 Answers

The problem is that the environment isn't what you expect.

You don't say whether the cron is running as your user, or as root, but, in either case, you can test to see what the environment looks like by adding another cron entry of:

* * * * * /usr/bin/env > /path/to/your/home/directory/env.txt

Let that run once, then pull it out, and look at the file.

Instead of using /usr/bin/env to try to find a Ruby to run your code, define the Ruby explicitly:

* * * * * /path/to/the/ruby/you/want /usr/local/src/hello/hello.rb >> /usr/local/src/hello/hello.log 2>&1

You can figure out which Ruby you want by using:

which ruby

Alternately, instead of relying on /usr/bin/env in your #! line, define your Ruby there.

Using /usr/bin/env ruby in your code is a convenience when you're using something like RVM or rbenv, and switching between versions of Ruby. It's not a good choice when you're putting something into "production", whether it's on your machine in your own account, or on a production host running as root.

If you are on Linux or Mac OS, try man 5 crontab for more information. Also, "Where can I set environment variables that crontab will use?" should be very useful.

like image 59
the Tin Man Avatar answered Sep 28 '22 09:09

the Tin Man


env searches only in the existing PATH variable. crond creates the process that is run as your user name. So the PATH is minimal. You have to set up your environment variables in the script itself

like image 20
jim mcnamara Avatar answered Sep 28 '22 10:09

jim mcnamara