snippets / class to parse bash variable from a script

Language: Ruby - First posted by enki on 2007-09-14 09:45 (1 year)
Link to the snippet: http://www.friendsnippets.org/snippet/9/

This class allow you to parse variable in a bash script from ruby . It retourn an array of variables. bash array is also saved as ruby array.

 1 #!/usr/bin/ruby
2 #
3 # how to use it :
4 # ovars=EnvBash.new(file)
5 # bash_vars=ovars.vars
6 #
7
8
9 class MultiRegexp < Regexp
10 def matches(str)
11 str.scan(self) do
12 yield Regexp.last_match
13 end
14 end
15 end
16
17
18 class EnvBash
19 attr_reader :bash_env
20
21 def initialize(source)
22 bash_script ="\
23 source #{source}
24 set
25 "
26 @bash_env = `#{bash_script}`
27 end
28
29 def vars
30 bvars=Hash.new
31 re=MultiRegexp.new('(\w*)=(.*)$', true)
32 re.matches(@bash_env) { |i|
33 if (i[1] != "")
34 if i[2] =~ /\(([^\)]*)\)/
35 ta=Array.new
36 re_a=MultiRegexp.new('\[\d*\]=\"([^"]*)\"', true)
37 re_a.matches($1) { |j|
38 ta.push(j[1])
39 }
40 bvars[i[1]]=ta
41 elsif
42 bvars[i[1]]=i[2]
43 end
44 end
45 }
46 return bvars
47 end
48 end
49
50 # test on a pkgbuild (archlinux)
51 bashvars=EnvBash.new("/var/abs/kernels/kernel26/PKGBUILD")
52
53 bvars=bashvars.vars
54 puts "#{bvars['pkgname']}-#{bvars['pkgver']}-#{bvars['pkgrel']}"
55
56 if bvars['source'].instance_of?(Array)
57 puts "sources : "
58 bvars['source'].each { |src|
59 puts src
60 }
61 end
In order to post a comment, you should have a friendsnippet account. Please sign-in.

0 comments

Sep '07
  • This class allow you to parse variable in a bash script from ruby . It retourn an array of variables. bash array is also saved as ruby array.

Common Tags



snippet History

Sep '07