Bash – Setting environment vars containing space with env

bashenvenvironment-variables

I'm trying to use env to set environment variables (read from another source, say for example a file) for a subprocess. Essentially, I am attempting the following:

env VALUE=thisisatest ./somescript.sh

If, for example, somescript.sh was:

echo $VALUE

Then this would print thisisatest as expected. But I would like to load the variables from a file. I've gotten to this point:

env $(cat .vars | xargs -d '\n') ./somescript.sh

But, I run into trouble when any of the variables contain spaces (and quotes don't work as expected). So for example:

env $(echo 'VALUE="this is a test"' | xargs -d '\n') ./somescript.sh

Will error with

env: is: No such file or directory

And trying:

env $(echo 'VALUE="thisisatest"' | xargs -d '\n') ./somescript.sh

Will give me the unexpected:

"thisisatest"

I assumed this would work properly since running env VALUE="thisisatest" ./somescript.sh prints it without the quotes.

From the error, I glean that for some reason env is not understanding that the quotes mean that the value that follows should be a string. However, I'm unsure how to interpolate these vars in a way that the quotes are correctly interpreted.

Can anyone provide any hints for how I could accomplish this?

Thanks!

Best Answer

You need double quote in command substitution, otherwise, the shell will perform field splitting with the result of command substitution:

$ env "$(echo 'VALUE="this is a test"')" ./somescript.sh
"this is a test"

For env reading from file, you must let the shell does field spliting, but set IFS to newline only, so your command won't break with space:

$ IFS='
'
$ env $(cat .vars) ./somescript.sh

If you want to read from file, it's better if you just source (aka dot) the file in somescript.sh:

#!/bin/bash

. .vars
: The rest of script go here