From: David Masover Date: 2009-08-08T07:53:59+09:00 Subject: Re: how to "source" a file? On Friday 07 August 2009 02:55:11 pm Glenn Jackman wrote: > Since Ruby is not Bash, you have to parse the file: > > File.foreach("myenv") do |line| > line.chomp.scan(/^export (.+?)=(.*)$/) do |name, val| > ENV[name] = val > end > end > > p ENV['FOO'] # => "bar" That's pretty fragile -- it would severely limit what you can put in the file. There are a few ways of doing this, depending on your goal. One would be to run a bash (or better yet, sh) script as a wrapper around your Ruby script -- that is, if your command is installed as /usr/local/bin/foo, have it be a shell script which does this: #!/bin/sh . ~/.myenv exec /usr/lib/foo/foo.rb $@ Another hack I've used, when I wasn't sure whether or not I'd need those variables, is to have bash execute the file, and then tell me. If you only need one variable, this is easy: ENV['FOO'] = `source ~/.myenv && echo -n $FOO` If you wanted all of the variables, here's one (clumsy) way to do it without having to (really) parse anything: require 'yaml' s = `source ~/.myenv && ruby -e 'require "yaml"; print ENV.to_hash.to_yaml` Yaml.load(s).each_pair{|k,v| ENV[k]=v} I realize I could've made that less ugly, but I'm not sure there's a good way to make it pretty. It's essentially the same as extracting a single variable, except that it invokes another Ruby interpreter to dump the entire environment as a yaml stream. I did this because it's a lot easier to just throw the yaml parser at the problem than try to parse the output of something like 'env' -- I couldn't even figure out which environment variables existed, otherwise. About the only way I could "improve" it is by streaming that Yaml generation/parsing, but if anyone has an environment big enough for it to matter, they've already got problems. One final way would be to add a 'source ~/.myfile' to any other programs you try to run -- since you mentioned EDITOR, I'm assuming that's why.