简体   繁体   中英

Environment variables in ruby script on Linux

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.

Eg 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM