globewalldesk globewalldesk - 3 years ago 247
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

environment variable with the command
echo $PATH
. In Rails,
(and the similar
) is an environment variable with values such as "development" and "production". But on the command line,
returns the unhelpful string
(as you'd expect) and
returns nothing (presumably because that's not what the environment variable is called). I've also tried
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
command, and it's not there.

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

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download