Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In an executable file, you specify the environment using a shebang:

#!/usr/bin/env ruby

# ruby code here

But what if you want to specify multiple possible environments? For example, if you have multiple versions of Ruby installed, you may want to do something like

#!/path/to/better/ruby/version
#!/path/to/alternative/ruby/version

# ruby code here

How can you specify multiple possible environments for a single executable file?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

The short answer is that you can't.

The idea behind using #!/usr/bin/env ruby instead of simply #!/usr/bin/ruby is to use whatever ruby binary is first in the user's path. Then your script doesn't depend on ruby being in the same place on every system; after all, a 'normal' ruby location might be /usr/bin/ruby, /usr/local/bin/ruby, /opt/ruby-1.8.7/bin/ruby, etc...

If you DID want to hardcode some values or do some searching logic, you could always make a wrapper shell script:

#!/bin/sh

for ruby in /usr/bin/ruby /usr/local/bin/ruby
do
    if [ -x "$ruby" ]
    then
        "$ruby" myscript.rb
        break
    fi
done

And if you're sufficiently motivated, you could even embed a ruby (or other) script inside the shell script.

share|improve this answer
    
That makes sense. I plan to run this script on multiple machines, each of which has a different path to Ruby 1.9, and they don't all use Ruby 1.9 as the default interpreter. I'll try using the wrapper script. Thanks! –  vote539 Aug 15 '12 at 15:43
add comment

I'm going to contradict mrb and say that you can do alternates, without changing the "#!" line.

Suppose you have a ruby script with #!/usr/bin/env ruby as the first line.

You want /path/to/better/ruby/version/whatever to run the script, you set the PATH environment variable to have /path/to/better/ruby/version first:

PATH=/path/to/better/ruby/version:$PATH  whatever_script_name_is

You want /usr/local/bin/ruby to run the script? Set PATH appropriately:

PATH=/usr/local/bin:$PATH  whatever_script_name_is

Note that fiddling with PATH can cause other problems in the case that the ruby executable you want to run the script resides in the same directory with other alternate programs. For example, if /usr/local/bin had BSD cat, grep, sed in it as well as ruby, then when you set PATH=/usr/local/bin:$PATH you will get the BSD executables instead of Linux executables. That could case a problem.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.