Setting variables with spaces within .env
Solution 1
If your command is just a shell command, you could run your command in a subshell like this:
( . .env ; echo "$TEST" )
The source
or .
builtin has no problem with assignments containing spaces. It will set the variables in the .env
file in the current shell's environment.
In the more likely case of calling an external program, you'll also have to add 'export' to each assignment in your env
file like this:
export TEST="hello world"
This is necessary because source
does not export assigned variables as env
does, i.e. they are set inside the subshell only but not in the environment of another process started inside that subshell.
Solution 2
juste put the word that contains the space between " ".
Related videos on Youtube
ThomasReggi
Updated on June 04, 2022Comments
-
ThomasReggi almost 2 years
I have a
.env
file with a bunch of variables and I just came across an error.One of the variables has spaces.
TEST="hello world"
So when I run this, learned about in this answer here.
env $(<.env)
I get this error.
env: world"': No such file or directory
How do I set variables with spaces within .env?
-
glenn jackman about 9 yearsYou just need to quote the file contents:
env "$(<.env)"
-
ThomasReggi about 9 years@glennjackman
env "$(<.env)" echo $TEST
seems to print a blank line.
-
-
ThomasReggi about 9 yearsI don't have a
test.env
file I don't understand what that is. Let's say mycmd
is just toecho $TEST
so from your example( . .env ; echo $TEST )
does not work it gives me-bash: world: command not found
. -
Michael Jaros about 9 yearsAh, sorry, I thought
.env
was just the extension. I'll modify. -
Isaac Freeman almost 6 years"The source or . builtin has no problem with assignments containing spaces" is incorrect. Un-quoted spaces will cause bash to think the word after the space is a command, that's why OP is getting "command not found". The values after the = need to be quoted if they contain spaces.
-
Michael Jaros almost 6 yearsThank you for your feedback. Let me share my thoughts on that: (1) The space in the OP's example is quoted, so my statement is correct in that context. (2) As I noted in the question comments, just quoting the command substitution would probably be sufficient in most situations, but it would not work with the example provided by glennjackman. (3) The actual problem here is that the quotes read from
.env
in the command substitution are not interpreted by Bash, then word splitting occurs, andenv
interprets the second argumentworld"
as a command (env NAME=value COMMAND ARG ...
). -
Qinjie about 2 yearsIf the value contains
"
, escape inner double-quote with\"
. For example,MESSAGE="Lets say \"Hi\""