Home > Uncategorized > Ruby sidebar: Using rvm on the shebang (#!) line in a script

Ruby sidebar: Using rvm on the shebang (#!) line in a script

May 4, 2012 3 Comments »

Just throwing this up here because I didn’t find it elsewhere.

I want to run ruby scripts from the command line or in a cronjob, and I do not want to always have to type “ruby scriptname”.

But, I use rvm. I want to run a particular ruby, maybe identified by an alias, maybe with a specific gemset.

It turns out you can use the env program with rvm do to accomplish this.

  1.     #!/usr/bin/env  rvm 1.9 do ruby
  2.    
  3.     require 'mygem'
  4.     o = MyGem.new
  5.     # blah blah blah

In this example, 1.9 is the name of the ruby (actually, an rvm alias) I want to use, and it could just as easily specify a gemset as well (e.g., 1.9@mygems).

If you’re running in cron, don’t forget you need to load the environment variables first. Here I use the bash . command to source my .bashrc.

  54 9-16 * * 1-5 . /Users/dueberb/.bashrc; /Users/dueberb/bin/exercise

Nothing fancy, but worth knowing.

Tags:

Comments:3

Leave my own
  1. Jonathan Rochkind
    May 4, 2012 at 3:44 pm

    If you’re running in a cronjob anyway, you could also just

       54 9-16 * * 1-5 . /Users/dueberb/.bashrc; rvm 1.9 do ruby /Users/dueberb/bin/exercise
    

    I’ve been experimenting with rbenv instead or rvm lately, especially on production servers. I’m liking it, it’s simpler, easier to understand, things go wrong less and i know how to fix em when they do. But i’m not sure if it would have the shebang line trick feature like that.

  2. Jonathan Rochkind
    May 4, 2012 at 3:45 pm

    (ha, good job with markdown in your comments, it looks like! What software do you use for your blog?)

    • mark
    • down
    • list
  3. Sands Fish
    October 20, 2012 at 2:48 pm

    Jonathan, I wish I had found out about rbenv just days earlier so I wouldn’t have done all kinds of unholy things to my pristine new Macbook’s environment to get rvm to install (like installing alternate GCC compilers into the XCode setup. cry)

    Thought looking at it, it doesn’t manage gemsets, which for me is a huge value, since most of my issues when running different Rails apps on the same machine end up being problems with various gems that are present or not.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>