Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell out from ruby while setting an environment variable

Tags:

I need to shell out to a process while setting an environment variable for it. I tried this one-liner:

system "RBENV_VERSION=system ruby extconf.rb" 

This syntax works in shell script but not from ruby. (Update: turns out this syntax works from ruby after all, but I failed to see its effect due to my particular use-case.)

So I'm doing this:

rbenv_version = ENV['RBENV_VERSION'] ENV['RBENV_VERSION'] = 'system' begin   system "ruby extconf.rb" ensure   ENV['RBENV_VERSION'] = rbenv_version end 

I'm forced to such a long expression because I don't want to override the environment variable permanently if it already had a value.

Anything shorter that comes to your mind?

like image 542
mislav Avatar asked Nov 28 '11 19:11

mislav


People also ask

How do you pass an environment variable in Ruby?

Passing Environment Variables to Ruby To pass environment variables to Ruby, simply set that environment variable in the shell. This varies slightly between operating systems, but the concepts remain the same. To set an environment variable on the Windows command prompt, use the set command.

How do you make a shell variable into an environment variable?

Setting an Environment Variable To output the value of the environment variable from the shell, we use the echo command and prepend the variable's name with a dollar ($) sign. And so long as the variable has a value it will be echoed out. If no value is set then an empty line will be displayed instead.

How do you set an environment variable that is accessible from Subshell?

The easiest way to set environment variables is to use the export command. Using export, your environment variable will be set for the current shell session. As a consequence, if you open another shell or if you restart your system, your environment variable won't be accessible anymore.

Where are Ruby environment variables stored?

You store separate environment variables in config/development. rb , config/testing. rb and config/production. rb respectively.


2 Answers

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

system accepts any arguments that Process.spawn accepts.

like image 93
Avdi Avatar answered Sep 20 '22 16:09

Avdi


Ruby 1.9 includes Process::spawn which allows an environ hash to be provided.

Process::spawn is also the foundation for system, exec, popen, etc.
You can pass an environment to each.

Under Ruby 1.8, you may want to consider the POSIX::Spawn library,
which provides the same interfaces

like image 44
rtomayko Avatar answered Sep 17 '22 16:09

rtomayko