1
votes

I'm using the oh-my-zsh dotenv plugin, which loads .env file, if it exists, whenever I cd into a project directory.

I know it works because I can see my custom environment vars set when I run the set cmd.

I can can also echo my custom environment variable from command line:

$ echo $FOO
'foo'

However, I cannot access this environment variable via the env command or Ruby:

$ irb
2.4.1 :001 > ENV['FOO']
nil

How can I make sure environment variables loaded from my .env are accessible from Ruby?

1
does it work if you require 'dotenv/load' ? - whodini9
I'm not using the dotenv gem (just the oh-my-zsh plugin) as I was under the impression that the shell plugin would export the vars automatically. - doremi
It should. Have you tried running export FOO=test and then irb: ENV['FOO'] ? That works here in iTerm2 on Mac OS. - Frederik Spang
If I manually export, then yea, that works. I was looking at this SO post and I think the issue is that the vars are only shell-local, which env cannot see. But I'm not sure how to fix that. - doremi
Is there a particular reason you don't want to use the gem? If the .env is in the working directory, it will work. Seems strange to rely on zsh functionality within your ruby program. You can easily exclude your .env file from a repo - whodini9

1 Answers

3
votes

Contrary to what is stated in the documentation of dotenv, you actually need to use the export keyword within the .env file in order to make the parameters available to the environment, e.g.

export FOO=foo

The only exception would be, if the parameter was already an environment variable. For example if it had been exported in ~/.zshrc or if it was already part of the environment zsh got when it started (e.g. PATH or HOME).


All dotenv does is automatically sourcing any .env file when changing into a directory. There is no additional "magic". That means .env needs to be a valid zsh script and its content is run in the context of the current shell session (essentially as if you typed it manually).

It also means that the usual rules apply. That is, just settings parameters makes them available to the current shell context only. In order to make them available as environment variables they need to be exported (either before, during or after being set). So unless a parameter has already been exported before, export is not really "optional" in .env.