ruby 将环境变量传递给 exec shell 命令的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9357132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right way to pass environment variables to exec shell command
提问by Kowshik
I'm using ruby 1.8.7 patch 249. Is the following the best/only way to pass environment variables to a shell command that I need to execute from my ruby program?
我正在使用 ruby 1.8.7 补丁 249。以下是将环境变量传递给我需要从 ruby 程序执行的 shell 命令的最佳/唯一方法吗?
fork do
ENV['A'] = 'A'
exec "/bin/bash -c 'echo $A'"
end
Process.wait
回答by Johannes Fahrenkrug
There is a really easy way:
有一个非常简单的方法:
system({"MYVAR" => "42"}, "echo $MYVAR")
All credit for this goes to Avdi: https://stackoverflow.com/a/8301399/171933
这一切都归功于 Avdi:https://stackoverflow.com/a/8301399/171933
回答by vaughan
For 1.8~ users - replicates 1.9 behaviour of exec. Same as OP's initial attempt though.
对于 1.8~ 用户 - 复制 exec 的 1.9 行为。与 OP 的初始尝试相同。
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'")
回答by Toon
I would do it in one line
我会在一行中完成
exec "/bin/bash -c 'A=hello; echo $A'"

