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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With