On Tue, Nov 19, 2013 at 1:08 PM, Robert Klemme
<shortcutter / googlemail.com> wrote:
> On Tue, Nov 19, 2013 at 8:43 AM, Gennady Bystritsky
> <gennady-ruby / bystr.com> wrote:
>>
>> On Nov 18, 2013, at 11:08 PM, Robert Klemme <shortcutter / googlemail.com> wrote:
>>
>>> On Tue, Nov 19, 2013 at 5:28 AM, Previn Lin <lists / ruby-forum.com> wrote:
>>>> I want to setup a tool, which set the env by source a csh file.
>>>>
>>>> Is there way to source csh env file in Ruby?
>>>>
>>>> For the attached test case, I wrote ruby as below, but seems don't work.
>>>>
>>>> #!/usr/bin/env ruby
>>>>
>>>> system "source test.csh"
>>>
>>> The shell cannot read a CSV file that way.  Even if using the output
>>> in Ruby would work that code breaks already in the shell.
>>
>> Why CSV? The original poster asked about CSH (Unix C Shell) environment propagation to Ruby.
>
> My bad. This is embarrassing.  I am sorry.

I still owe you a proper reply.  Here it is:

$ ./test.rb
a = Linux
$ cat test.rb
#!/usr/bin/env ruby

IO.popen(['csh', '-c', 'source test.csh && setenv']) do |io|
 io.each_line do |line|
   if %r{^([^=]+)=(.*)$} =~ line
     ENV[$1] = $2
   else
     warn "Cannot read line %p" % line
   end
 end
end

puts "a = #{ENV['SYSTYPE']}"

The code could be extended in the following ways:

1. more error checking (e.g. existence of test.csh)
2. handle variables with values that contain a newline
3. filter, e.g. include / exclude special variable names or by entries
already present in the current environment.

The last one is easy, just change one line

ENV[$1] ||= $2

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/