Possible Duplicate:
Exporting an Environment Variable in Ruby可能重复:在Ruby中导出环境变量
I need to set several environment properties from inside of ruby script.
我需要从ruby脚本中设置几个环境属性。
Normally, in bash, I do the following:
通常,在bash中,我执行以下操作:
$ export SOME_VAR=some_value
But in ruby, following (obviously) doesn't work:
但在红宝石中,以下(显然)不起作用:
irb(main):002:0> `export SOME_VAR=some_value`
(irb):2: command not found: export ASDF=1
=> ""
Is there a way to do it?
有办法吗?
3 个解决方案
#1
9
According to http://ruby.about.com/od/rubyfeatures/a/envvar.htm, you can just write:
根据http://ruby.about.com/od/rubyfeatures/a/envvar.htm,你可以写:
ENV['SOME_VAR'] = 'some_value'
#2
1
If you don't want this value to persist after script is finished, you can alter ENV
directly.
如果在脚本完成后不希望此值保持不变,则可以直接更改ENV。
ENV['SOME_VAR'] = 'some_value'
puts ENV['SOME_VAR']
# => some_value
If you do want persistence, then you probably (in addition to this) have to write this var to a ~/.bashrc
or similar file on your system.
如果你确实需要持久性,那么你可能(除此之外)必须将此var写入系统上的〜/ .bashrc或类似文件。
#3
1
Try `ENV['SOME_VAR'] = 'some_value'.
试试`ENV ['SOME_VAR'] ='some_value'。
You cannot make the effects of this persist in the environment executing the script, after the script is finished.
在脚本完成后,您无法在执行脚本的环境中产生此持久性的效果。
A trick that is being discussed in the comments to my answer, is to print valid shell code to the console, from your ruby script — this is not what you need, but it may be useful to know it could work that way too.
在我的回答的评论中讨论的一个技巧是从ruby脚本中将有效的shell代码打印到控制台 - 这不是你需要的,但是知道它也可以这样工作可能是有用的。
$ echo "puts 'export foo=bar'" > test.rb
$ echo $foo
$ source <(ruby test.rb)
$ echo $foo
bar
#1
9
According to http://ruby.about.com/od/rubyfeatures/a/envvar.htm, you can just write:
根据http://ruby.about.com/od/rubyfeatures/a/envvar.htm,你可以写:
ENV['SOME_VAR'] = 'some_value'
#2
1
If you don't want this value to persist after script is finished, you can alter ENV
directly.
如果在脚本完成后不希望此值保持不变,则可以直接更改ENV。
ENV['SOME_VAR'] = 'some_value'
puts ENV['SOME_VAR']
# => some_value
If you do want persistence, then you probably (in addition to this) have to write this var to a ~/.bashrc
or similar file on your system.
如果你确实需要持久性,那么你可能(除此之外)必须将此var写入系统上的〜/ .bashrc或类似文件。
#3
1
Try `ENV['SOME_VAR'] = 'some_value'.
试试`ENV ['SOME_VAR'] ='some_value'。
You cannot make the effects of this persist in the environment executing the script, after the script is finished.
在脚本完成后,您无法在执行脚本的环境中产生此持久性的效果。
A trick that is being discussed in the comments to my answer, is to print valid shell code to the console, from your ruby script — this is not what you need, but it may be useful to know it could work that way too.
在我的回答的评论中讨论的一个技巧是从ruby脚本中将有效的shell代码打印到控制台 - 这不是你需要的,但是知道它也可以这样工作可能是有用的。
$ echo "puts 'export foo=bar'" > test.rb
$ echo $foo
$ source <(ruby test.rb)
$ echo $foo
bar