How to specify rubygems path in environment-less Ruby script?

environment, path, ruby, rubygems

Solution

#!/bin/sh

#export LOAD_PATH=whatever 
#export RUBYLIB=whatever
#export RUBYOPT=whatever
#export RUBYPATH=whatever
#export RUBYSHELL=whatever
#export PATH=$PATH:whatever
exec ruby -x. $0 "$@"

#!/usr/bin/ruby
require 'rubygems'
require 'open4' # or whatever

# rest of ruby script here

This is a shell script that runs ruby with -x, which will cause the interpreter to skip lines until it finds `#!.*ruby`. This will give you a chance to restore the environment. The `.` after `-x` is a noop, you can take out the `.`, or replace it with a directory. Ruby will cd there before running the script.

I'm actually guessing that this is not really what you want, since this could have been done without any trickery by just making two scripts, one for the shell, one for Ruby. Perhaps the list of environment variables Ruby cares about will help...

Problem

I've written a data collection script for Cacti in Ruby and it runs fine from the command line but Cacti runs the script via "env -i" which strips the environment so Ruby can't find the rubygems library ("in `require': no such file to load -- rubygems (LoadError)"). How might I work around this?

Original source