why bash -l -c “CMD” makes ruby find my gem?

2019-08-08 10:57发布

问题:

In my ruby script,I required the gmail gem:

require 'rubygems'
require 'gmail'

when running in shell,it works ok:

ruby my-script.rb

while when I put it in a cron job,it failed to execuate:

* * * * * cd /to/script/directory;/usr/local/rvm/rubies/ree-1.8.7-2011.03/bin/ruby ./my-script.rb

the log shows that the gmail gem can not be loaded:

/usr/local/rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require': no such file to load -- gmail (LoadError)

well, when i do this(put the cmd in bash -l -c 'CMD'):

* * * * * /bin/bash -l -c 'cd /to/script/directory;/usr/local/rvm/rubies/ree-1.8.7-2011.03/bin/ruby ./my-script.rb'

it works ok again.

why?

ps.I know the arg -l make the bash a login shell,but does that make any difference?

回答1:

The -l parameter executes the command in a login shell, which means that it inherits your path and other settings from your shell profile. The cron job, if run without the login shell, will be run without any path environment variables set (such as those set by RVM), which results in the system being unable to find the referenced gems.



回答2:

rvm requires you use a shell login, see FAQ.



回答3:

I suspect you are loading RVM in your login script, ergo RVM will only be available in a login shell.