1

I have this shell script in a file named a.sh:

export A='a'
export B=b
export C=1
export D=$USER  # say $USER is root

There are some other similar files b.sh, c.sh, etc.

I need to read the shell file, say a.sh, from ruby script and convert it to a Ruby hash:

{ 'A' => 'a', 'B' => 'b', 'C' => 1, 'D' => 'root' }

How to achieve that?

1
  • You have your environment variables in ENV constant. Commented Apr 8, 2014 at 12:40

1 Answer 1

3

If you have run the bash script prior to the ruby one, you can get doing something like this:

Hash[([ 'A', 'B', 'C', 'D' ] & ENV.keys).map {|x| [x, ENV[x]] }]

where array [ 'A', 'B', 'C', 'D' ] contains valid variable names to create the Hash.

If you need to parse the bash script in ruby, do as follows:

vars = {}
IO.read('shell.sh').each do| line |
   if line =~ /^export\s([A-Za-z_][A-Za-z_0-9]*)=\s*(?:['"]([^'"]*)['"]|(.*))\s*$/
      (name, value) = [ $1, $2 || $3 ]
      value.gsub!( /\$(?:([A-Za-z_][A-Za-z_0-9]*)|{([^{}]+)})/ ) do| match |
         ENV[ match[1..-1] ]
      end
      vars[ name ] = value.gsub(/#.*/, '').strip
   end
end
vars
# => {"A"=>"a", "B"=>"b", "C"=>"1", "D"=>"malo"}
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I might not state clearly. The shell script is not executed prior to ruby script, I need to read the shell script in ruby script. So ENV doesn't contain those variables yet.
@МалъСкрылевъ: I know, tag markup is fun, but please don't :)
@МалъСкрылевъ Thanks for your answer. But that's still not what I want. Because shell.sh might be a real shell script, so I have to use shell to interpret it then get result from environment.
@EvanLi please be decided no will you run the script before, or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.