1. Computing

RVM and 'sudo'

By

RVM is great. However, there may be times where you must run Ruby scripts with RVM as root (or another user) via sudo. Your first attempt might be to do something like this.

$ rvm use 1.9.2
$ sudo ruby myscript.rb

However, this won't work at all. Remember that sudo will start a new subshell. That new subshell's environment will be completely different, and won't contain RVM, nor will it have access to your user's RVM without trying to hack in RVM's environment variables yourself.

RVM does come with a solution though, the rvmsudo command. It will pass on any environment variables that RVM set up to get you to the correct Ruby. This includes the $PATH as well has $GEM_HOME, $GEM_PATH and $BUNDLE_PATH variables.

So to run the script called asroot.rb, simply use the Ruby you want and run it with rvmsudo.

$ rvm use 1.9.2
$ ruby asroot.rb
This script must be run as root, aborting.
$ rvmsudo ruby asroot.rb
Reticulating splines...  DONE
$

There are some minor security concerns using rvmsudo. Since RVM adds you gem's bin path to the environment ahead of any system paths, gems could install duplicate commands that may be harmful to your system. As always, take caution when running commands as the root user, or any other user with elevated privileges.

  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Ruby Version Manager
  6. RVM and 'sudo'

©2014 About.com. All rights reserved.