I'm currently loading multiple variables into my shell (from a .env
file) like so:
eval $(grep '^VAR_1' .env) && eval $(grep '^VAR_2' .env) && ...
I then use them in a script like so: echo $VAR_1
.
Is there any way to condense this script into something like: eval $(grep ^('VAR_1|VAR_2')) .env
? Maybe needs something other than grep
CodePudding user response:
You may use this grep
with ERE
option to filter all the variable you want from .env
file:
grep -E '^(VAR_1|VAR_2)=' .env
This pattern will find VAR_1=
or VAR_2=
strings at the start.
To set variable use:
declare $(grep -E '^(VAR_1|VAR_2)=' .env)
# or
eval $(grep -E '^(VAR_1|VAR_2)=' .env)
CodePudding user response:
I would use source
(.
) command with process substitution:
. <(grep -e '^VAR_1=' -e '^VAR_2=' .env)
or
. <(grep '^VAR_[12]=' .env) # for this particular variables
The file .env
must be from a trusted source, of course.