globewalldesk globewalldesk - 10 months ago 69
Linux Question

Is there a way to return the value of the environment variable RAILS_ENV from the Linux command line?

In Linux, you can find the value of the

$PATH
environment variable with the command
echo $PATH
. In Rails,
RAILS_ENV
(and the similar
RACK_ENV
) is an environment variable with values such as "development" and "production". But on the command line,
echo RAILS_ENV
returns the unhelpful string
RAILS_ENV
(as you'd expect) and
echo $RAILS_ENV
returns nothing (presumably because that's not what the environment variable is called). I've also tried
env RAILS_ENV
and variants. Am I getting the syntax wrong, or what?

Am I right to think that basically the environment variable just doesn't exist until Rails is run? Well...I tried running a Rails server in one terminal, then opened another and then repeated the above commands; no dice.

Or is the problem that Linux, or my shell, doesn't track this environment variable? But...wouldn't it have to, being an environment variable? I tried looking for it in the output of the
env
command, and it's not there.

Is it possible that the only way to discover the value of the
RAILS_ENV
environmental variable is through Rails itself, e.g., by calling
Rails.env
?

UPDATE: this helpful discussion gives the command
rails r "puts Rails.env"
, but I was looking for a command that didn't call Rails itself.

Answer Source

You were right with echo $RAILS_ENV. It is likely not set, so it is defaulting to development. This is done within the Rails codebase.

$ export RAILS_ENV=development
$ echo $RAILS_ENV #=> development

In another console

# In a new window
$ echo $RAILS_ENV
$ rails runner "puts Rails.env" #=> development
$ RAILS_ENV=test rails runner "puts Rails.env" #=> test

No RAILS_ENV variable is set, to rails defaults to development

Here is the equivilent in Bash.

if [ -z "$RAILS_ENV" ]; then
  export RAILS_ENV="development";
fi
echo $RAILS_ENV
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download