How to execute setenv command inside ruby code

Viewed 96

I am trying to set an environmental variable inside the ruby code by below mentioned 3 methods. Like this:

one = `setenv HEMANT2 \"hi\"`

two = %x[ export HEMANT2=hi1]

there = system("setenv HEMANT \"hi\"")

And none of these 3 seems to be working. I am working on tcsh. Wondering what did I miss?

1 Answers

Environment variables belong to a process and are passed to their children. All of your lines above create a child shell process. The environment variable is changed in the child shell process, not its parent Ruby process.

Instead, use the ENV class.

ENV['HEMANT2'] = 'hi'

This will set the HEMANT2 environment variable in your Ruby process. But it will not change the environment variables in your shell.

$ cat ~/tmp/test.rb
ENV['HEMANT2'] = 'hi'
$ ruby ~/tmp/test.rb
$ echo $HEMANT2

$ 

Again, because environment variables belong to a process and are inherited by their children. ruby ~/tmp/test.rb forks a child process of your shell. It cannot set its parent's environment variables.


You can do it with a shell script, but only if you source it. source does not create a child process, it runs the commands in your shell.

$ cat test.sh
#!/bin/sh

HEMANT2=hi

$ sh test.sh
$ echo $HEMANT2

$ source test.sh
$ echo $HEMANT2
hi

This only works with shell scripts written for your shell.

Related