On Tue, 30 Aug 2005, Wybo Dekker wrote:


> command = "x=hello echo $x";    pr(command,*sys(command)) # FAILS!

this doesn't even work from the shell:

     harp:~ > x=hello echo $x
     (newline)

this is because parameter expansion (of $x) occurs __before__ the x=hello is
set for the local environment.  you can see this by doing:

     harp:~ > x=hello env|egrep ^x=
     x=hello

so here the 'x' is looked for __after__ local env vars are set.  this is
detailed here:

     http://www.gnu.org/software/bash/manual/bashref.html#SEC48

alternatives:

   using session:

     harp:~ > cat a.rb
     require 'session'

     sh = Session::new

     sh.execute 'x=hello'
     stdout, stderr = sh.execute 'echo $x'

     p stdout
     p sh.status

     harp:~ > ruby a.rb
     "hello\n"
     0


   another way:

     def sys cmd, env = {}
       merge_env(env){ [ %x[{ #{ cmd } ;} 2>&1], $?.success?, $?.exitstatus ]}
     end
     def merge_env new_env, &block
       push_env(ENV.to_hash.merge(new_env), &block)
     end
     def push_env new_env, &block
       @env_stack ||= []
       cur_env = ENV.to_hash
       @env_stack << cur_env
       set_env new_env
       if block
         begin
           block[new_env]
         ensure
           pop_env
         end
       else
         cur_env
       end
     end
     def pop_env
       @env_stack ||= []
       old_env = @env_stack.pop
       if old_env
         set_env old_env
       else
         old_env
       end
     end
     def set_env env
       ENV.clear
       env.each{|k,v| ENV["#{ k }"] = "#{ v }"}
       ENV.to_hash
     end


use like

   sys 'foobar', 'PATH' => './bin', 'LD_LIBRARY_PATH' => './lib'

hth.

-a
-- 
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze.  --Nagarjuna
===============================================================================