Is there a utility to read environment variables from an env file and then run a command (more lightweight than foreman)?
Solution 1
You can source the environment file in the active shell and run the program:
sh -ac ' . ./.env; /usr/local/bin/someprogram'
The -a
switch exports all variables, so that they are available to the program.
Solution 2
Another alternative is envdir
:
envdir runs another program with environment modified according to files in a specified directory.
- The daemontools original: http://cr.yp.to/daemontools/envdir.html
- A python port: https://github.com/jezdez/envdir
Solution 3
I tried source .env
and it worked like a charm. Unfortunately, none of the other solutions posted here worked for me.
Solution 4
This works:
env $(cat .env | tr "\\n" " ") myprogram
but obviously doesn't check the format of the .env
file for correctness, which a utility program would do.
Related videos on Youtube
wodow
Updated on September 18, 2022Comments
-
wodow over 1 year
foreman
can read .env files and set environment variables from the contents, and then run a programe.g.
foreman run -e vars.env myprogram
...but it does a lot of other things (and is primarily concerned with starting things using its Procfile format).
Is there a simpler (Linux/Unix) tool that's just focussed on reading .env files and executing a command with the new environment?
Example environment file (from http://ddollar.github.io/foreman/#ENVIRONMENT ):
FOO=bar BAZ=qux
-
Daniel Widrick over 10 yearsCan you post an example .env file? I suspect
bash .env
orsh .env
may work? -
wodow over 10 years@IVlint67 I've improved the question a little.
-
-
Marco over 10 years1) The
cat
is not necessary, just writetr "\\n" " " < .env
2) This breaks if multi-line assignments are used. -
fiatjaf over 5 years
bash -ac 'source .env && ./program'
-
Marco over 5 years@fiatjaf Why would you use bash in this case if the POSIX shell does the job and you need no feature that actually requires bash? Furthermore, bash is not available by default on all systems (e.g. FreeBSD).
-
fiatjaf over 5 yearsOh, right, makes sense, I think your way is better, then. I was just providing the Bash alternative because I felt more comfortable writing it.
-
m_floer about 5 yearsThis post mentions some complementary features between
envdir
,runit
, andchpst
; namely ability to have changed env vars reflect in the state of the process being run. The post is about docker but it's not limited to docker. blog.ghaering.de/post/docker-as-vm [ archive.org: web.archive.org/web/20190321165332/https://blog.ghaering.de/… ] -
LennyLip almost 3 yearsThis works only for valid bash (strings like
export KEY=VALUE
, notKEY=VALUE
)