Issue
I see great question and answer, but I can not adopt it to my command:
$ echo 'TEST="value with spaces"' > .env
$ cat .env
TEST="value with spaces"
$ env $(cat .env | xargs -d "\n" ) echo $TEST
env: with: No such file or directory
$ export $(cat .env | xargs -d "\n" ) echo $TEST
-bash: export: `spaces"': not a valid identifier
I can use eval
but it spoils my environment:
$ eval $(cat .env | xargs -d "\n" ); echo $TEST
value with spaces
$ echo $TEST
value with spaces
Solution
If you want temporary environment variables from a file without otherwise changing your execution environment, some options are:
- Use a subshell. The new environment will only apply to the commands between
( )
.
( source .env ; echo "$TEST" )
- Use a child bash process and tell it to read environment variables from the file. Other programs may have a similar way to pass in an environment, either via an environment variable or a command line option. You'll have to check their manuals.
BASH_ENV=.env bash -c 'echo "$TEST"'
Note a potential pitfall with something like:
TEST="thing with spaces" echo "|$TEST|" #prints ||
Scoped environment variables are given to the program when it executes, but variables are substituted before the program executes. Whatever solution you end up using, you have to ensure the environment you want is in place before you attempt to reference variables from that environment.
Answered By - tjm3772 Answer Checked By - Dawn Plyler (WPSolving Volunteer)