[ACCEPTED]-Right way to pass environment variables to exec shell command-ruby

Accepted answer
Score: 40

There is a really easy way:

system({"MYVAR" => "42"}, "echo $MYVAR")

All credit for 1 this goes to Avdi: https://stackoverflow.com/a/8301399/171933

Score: 3

For 1.8~ users - replicates 1.9 behaviour 1 of exec. Same as OP's initial attempt though.

def exec_env(hash, cmd)
  hash.each do |key,val|
    ENV[key] = val
  end
  exec cmd
end

exec_env({"A"=>"A"}, "/bin/bash -c 'echo $A'")
Score: 1

I would do it in one line

exec "/bin/bash -c 'A=hello; echo $A'"

0

More Related questions