Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting an Environment Variable in Ruby

How do I export an environment variable from within a Ruby script to the parent shell? For example, implementing a naïve implementation of the read Bash builtin:

#!/usr/bin/ruby  varname = ARGV[0] ENV[varname] = STDIN.gets  # but have varname exported to the parent process 
like image 512
wilhelmtell Avatar asked Apr 18 '10 00:04

wilhelmtell


People also ask

How do I pass an environment variable in 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 I export an environment variable?

To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.

Where are Ruby environment variables stored?

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


1 Answers

You can't export environment variables to the shell the ruby script runs in, but you could write a ruby script that creates a source-able bash file.

For example

% echo set_var.rb #!/usr/bin/env ruby varname = ARGV[0] puts "#{varname}=#{STDIN.gets.chomp}" % set_var.rb FOO 1 FOO=1 % set_var.rb BAR > temp.sh ; . temp.sh 2 % echo $BAR 2 % 

Another alternative is that using ENV[]= does set environment variables for subshells opened from within the ruby process. For example:

outer-bash% echo pass_var.rb #!/usr/bin/env ruby varname = ARGV[0] ENV[varname] = STDIN.gets.chomp exec '/usr/bin/env bash' outer-bash% pass_var.rb BAZ quux inner-bash% echo $BAZ quux  

This can be quite potent if you combine it with the shell's exec command, which will replace the outer-shell with the ruby process (so that when you exit the inner shell, the outer shell auto-exits as well, preventing any "I thought I set that variable in this shell" confusion).

# open terminal % exec pass_var.rb BAZ 3 % echo $BAZ 3 % exit # terminal closes 
like image 194
rampion Avatar answered Sep 19 '22 12:09

rampion