将环境变量传递给exec shell命令的正确方法[duplicate]

时间:2022-05-03 23:52:52

This question already has an answer here:

这个问题已经有了答案:

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。下面的方法是将环境变量传递给shell命令的最好的/唯一的方法吗?

fork do       
   ENV['A'] = 'A'
   exec "/bin/bash -c 'echo $A'"
end

Process.wait

4 个解决方案

#1


24  

There is a really easy way:

有一个很简单的方法:

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

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

这一切归功于Avdi: https://*.com/a/8301399/171933

#2


11  

The docs for Ruby's exec method seem incomplete, but it does say there is an optional first argument called env, so presumably that specifies the environment. With an educated guess and some experimenting, I found out that the right way to use it is this:

Ruby的exec方法的文档看起来不完整,但是它确实说有一个可选的第一个参数叫env,所以可以假定它指定了环境。通过有根据的猜测和一些实验,我发现正确的使用方法是:

exec({"A"=>"A"}, "/bin/bash -c 'echo $A'")

EDIT 1: Sorry, doesn't work for older versions of Ruby.

编辑1:对不起,Ruby的旧版本不适用。

#3


3  

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

对于1.8~用户-复制1.9的exec行为。和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'")

#4


0  

I would do it in one line

我用一行来写。

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

#1


24  

There is a really easy way:

有一个很简单的方法:

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

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

这一切归功于Avdi: https://*.com/a/8301399/171933

#2


11  

The docs for Ruby's exec method seem incomplete, but it does say there is an optional first argument called env, so presumably that specifies the environment. With an educated guess and some experimenting, I found out that the right way to use it is this:

Ruby的exec方法的文档看起来不完整,但是它确实说有一个可选的第一个参数叫env,所以可以假定它指定了环境。通过有根据的猜测和一些实验,我发现正确的使用方法是:

exec({"A"=>"A"}, "/bin/bash -c 'echo $A'")

EDIT 1: Sorry, doesn't work for older versions of Ruby.

编辑1:对不起,Ruby的旧版本不适用。

#3


3  

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

对于1.8~用户-复制1.9的exec行为。和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'")

#4


0  

I would do it in one line

我用一行来写。

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