If you have
my_command like this:
running it obviously prints
source my_command will run the script, in the current shell, which will just produce the assignments as output. You would use
my_command didn't print the assignments, but executed then directly.
export $(my_command) will take the output of the script, and pass it to export, which will put the variables in the current shell environment, but it only works as long as the variables in question don't contain whitespace or glob characters, since the command substitution is unquoted. Putting
"$(my_command)" in quotes doesn't really help, because then
VAR1=some_value\nVAR2=other_value as one argument, and only
VAR1 is set.
Note that having running
export $(my_command) or setting variables in any other way within another script will not set those variables in the parent shell. If you want the assignments in your interactive shell, you must run them there, but you could wrap the assigments in a function or
source a script that makes the assignments.
One, obvious solution would be to do what
ssh-agent does, and have the script output
export commands for the variables it sets. Then it would be enough to run
If we don't want to do that, we can use
set -a before the script to have the shell automatically export any variables that are set.
$ set -a
$ eval "$(my_command)"
In Bash, we can use
declare -p to check that the variables are exported (
$ declare -p VAR1 VAR2
declare -x VAR1="some_value"
declare -x VAR2="other_value"
eval here will allow the script to output quoted strings like
VAR1="foo bar", and they will be handled correctly.
eval will also run anything else the script
my_command outputs, not just assignments, but if you didn't trust
my_command, you shouldn't run it at all.