Search code examples
bashenvironment-variablesenv

Setting variables with spaces within .env


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?


Solution

  • 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.