4 ms·
Would not sh -c '. .env; echo $MY_VAR' do the same thing? (I am not in front of a shell at the moment.)
by mongol 2y ago
Would not
sh -c '. .env; echo $MY_VAR'
do the same thing? (I am not in front of a shell at the moment.)
- mixmastamyk 2y agoSeems to work.
- kelnos 2y agoThat would, but unless each line in your .env file is prefixed with "export", those env vars won't get passed into any subprocesses you run.
- deleted 2y ago[deleted]
- iokanuon 2y agoYou'd need to `set -a` or pass the `-a` as a flag to have them auto-exported though, so: sh -ac '. ./.env; ./prog' Also if you use the `.` builtin it's a good idea to specify the path with a slash in it, so that `.` doesn't search $PATH first.
- datascienced 2y agoNow that is unixy!
- emmanueloga_ 2y agoThere are like a couple dozen different ways to do this... I have this on my .bashrc: alias loadenv='export $(xargs <.env)' source: [1] -- 1: https://stackoverflow.com/a/60406814/855105 https://stackoverflow.com/a/60406814/855105
- geysersam 2y agoVery nice! Thanks for the suggestion. Seems more Unix-esque. Are there any important drawbacks of this version compared to the dedicated tool? (dotenv or dotenvx)
- kilroy123 2y agoI can't believe I've never thought of doing this until now.
- iokanuon 2y agoThat will break if there's comments in the file, or if any one of the variables' values contain spaces. You can use `set -a` to load .env into an existing shell instance instead: loadenv() { set -a source ./.env set +a }
- emmanueloga_ 2y agoCool! This answers a question someone had in this thread. ... except I'm thinking this may `set +a` if the environment already had `set -a`, which maybe could cause problems? I wonder if it would make sense to record the existing status of "-a" (allexports) an set it / unset it as necessary.
- iokanuon 2y agoYou could do that, and it'd still be POSIX-shell comptible: loadenv() { case "$-" in *a*) source ./.env ;; *) set -a; source ./.env; set +a ;; esac } Although I have yet to see a long shellscript utilise `set -a` globally :)