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?