11

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?

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which question you just answered correctly. But the env variables come from crond, not your user profile. That is whole point.
I ended up using /usr/local/bin/ruby .../hello.rb.
3

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

2 Comments

crond can run crontabs for root, or for any user on the system.
Correct but IT DOES NOT LOG IN AS YOU. So the variables are not yours, you inherit them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.