Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I source environment variables for a command shell in a Ruby script?

I'm trying to run some third party bash scripts from within my ruby program.

Before I can run them they require me to source a file. On the command line it all works fine but within Ruby it doesn't work. I've found out that system commands will open a new child shell process and any sourcing will be done in that and can't be seen from the parent shell process running the Ruby script. When the system call ends, the child shell is also killed.

How do i get round this problem?

like image 440
robodisco Avatar asked Jan 26 '10 11:01

robodisco


3 Answers

Do this:

$ source whatever.sh
$ set > variables.txt

And then in Ruby:

File.readlines("variables.txt").each do |line|
  values = line.split("=")
  ENV[values[0]] = values[1]
end

After you've ran this, your environment should be good to go.

like image 192
Geo Avatar answered Sep 18 '22 22:09

Geo


I'm not sure if I understand your question correctly. Do you try to source a shell script before running another one? In this case the answer is simple:

#!/bin/env ruby
system "source <path_to_source_file> && <command>"

If the source file contains variables which your command should use you have to export them. It is also possible to set environment variables within your Ruby script by using ENV['<name_of_var>'] = <value>.


Update: Jan 26, 2010 - 15:10

You can use IO.popen to open a new shell:

IO.popen("/bin/bash", "w") do |shell|
  shell.puts "source <path_to_source_file>"
  shell.puts "<command>"
end
like image 40
t6d Avatar answered Sep 21 '22 22:09

t6d


This is horrible, but..

env = %x{. /some/shell/script/which/setups/your/env && env}
env.split("\n").each do |line|
  key, value = line.split("=", 2)
  ENV[key] ||= value unless value.nil? or value.empty?
end
like image 40
Marc Avatar answered Sep 18 '22 22:09

Marc