Setting environment vars containing space with env
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
This works:
env -S "`cat .vars`" command
First, in your file, you'll need to quote the variable value.
VALUE="This has spaces"
Then use the -S
flag to parse the vars (which strips out the quotes).
env -S "`cat .vars`" command-refers-to-env-vars
You can't refer to $VALUE
in the command, of course, because the command is evaluated by the shell prior to the action of env
. To do that you'd need to use the following:
( . .vars ; echo $VALUE )
The parentheses open a subshell so that you don't pollute your shell with all the definitions in .vars
. However, the variables are available only to the shell. They're not actually in the env
, so processes wouldn't be able to access them with process.ENV.VALUE
or getenv("VALUE")
as with the env -S
invocation.
You can combine both with
( . .vars ; env -S "`cat .vars`" command-refers-to-envs $VALUE )