Linux上的ruby脚本中的环境变量 [英] Environment variables in ruby script on Linux

查看:62
本文介绍了Linux上的ruby脚本中的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一台服务器上有一个简单的ruby脚本,它可以执行某些操作(而不是相关问题).有时直接从命令行运行,有时从cron作业执行的bash脚本运行,有时甚至是fail2ban动作的结果.

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.

该脚本使用环境变量(例如 FOO = bar ),而我使用通过将 FOO = bar 放在我项目中的.env文件中,可以加载dotenv gem.

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.

但是,在某些情况下,未加载环境变量会导致脚本失败,特别是在脚本由自动化流程或bash脚本执行而不是直接运行脚本的情况下.

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.

例如,脚本中仅包含以下内容(.env文件存在并已填充):

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']

然后我运行/path/to/myscript.rb .它输出"bar".

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

但是,如果我将行/path/to/myscript.rb 放置在test.sh文件中并运行 ./test.sh ,则不会输出任何内容.env没有被加载.如果在ruby调用之前加上 export FOO ="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.

如何确保按需加载我的.env变量?

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

推荐答案

.env文件是从项目的根目录加载的.特别是在您当前的目录中.在执行脚本之前,请尝试移至包含.env文件的目录.

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

更新:

您可以从脚本路径中加载.env文件,而无需将其移动到此处:

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)

这篇关于Linux上的ruby脚本中的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆