Environment variables in ruby script on Linux

2019-09-08 04:08发布

问题:

I have a simple ruby script on one of my servers that does some things (not relevent for the question). It is sometimes run directly from the command line, sometimes from a bash script executed by a cron job and sometimes as the result of a fail2ban action.

The script uses an environment variable (let's say FOO=bar) and I use the dotenv gem to load it by placing FOO=bar in a .env file in my project.

However, in certain cases the environment variable is not loaded resulting in the script failing, specifically whenever the script is executed by an automated process or bash script as opposed to me running it directly.

E.g say the script just has the following in it (and the .env file exists and is populated):

#!/usr/bin/env ruby
require 'dotenv'
Dotenv.load
puts ENV['FOO']

And I run /path/to/myscript.rb. It outputs 'bar'.

However, if I place the line /path/to/myscript.rb in a test.sh file and run ./test.sh nothing is output meaning the .env is not being loaded. If I precede the ruby call with export FOO="bar" it then works as expected.

How can I ensure my .env variables are loaded as required?

回答1:

The .env file is loaded from the root of your project. Specifically in your case from the current directory. Try moving into the directory containing the .env file before executing the script.

cd /path/to/ && ./myscript.rb

Update:

You can load the .env file from the script path without moving there:

config = File.absolute_path(File.join(File.expand_path(__FILE__), '..', '.env'))
Dotenv.load(config)