0

I've a command that outputs the environment variable to run particular program.

Say

$ outputenv --name <program name>
ENV_VARIABLE_1=<value1>;ENV_VARIABLE_2=<value2>

I want to use this output while running this program only for that instance.

$ <output of outputenv command> myprogram --options

Similar how I would run a program with env variables like.

$ ENV_VARIABLE_1=<value1>;ENV_VARIABLE_2=<value2> myprogram --options

Is there any way I can do it?

I tried

$ (outputenv --name myprogram) myprogram --options

and didn't help.

9
  • Looks like you have a trailing ) in that command: $(outputenv --name myprogram) myprogram --options). Remove that and it should work? Commented Aug 21, 2020 at 20:44
  • 1
    @AriSweedler, no, it still won't work, because the initial assignments are syntax; they need to be parsed in that form before any expansions are run. Commented Aug 21, 2020 at 20:48
  • Ahh, I see. So the need is to have a command like VAR1=x VAR2=y ./executable, with env vars separated by spaces not ;. Well in that case, $(outputenv --name myprogram | tr ';' ' ') to translate ; to spaces as desired Commented Aug 21, 2020 at 20:49
  • 1
    @AriSweedler, yes, you can, but it needs to be seen that way by the parser. Before asking me to repeat myself again, please, try $(echo MYVAR=hello) env, and you'll see it not work. Commented Aug 21, 2020 at 20:53
  • 1
    Let us continue this discussion in chat. Commented Aug 21, 2020 at 20:54

1 Answer 1

7

If you trust outputenv to generate safely shell-escaped output, then this is a job that eval is appropriate for:

( set -a; eval "$(outputenv --name myprogram)"; exec myprogram --options )

Starting a subshell with ( scopes the environment changes we're making to that single process; using set -a makes all subsequently-assigned variables be automatically exported; using eval causes the content within to be parsed as syntax; using exec makes the subshell be replaced with a copy of myprogram, avoiding an unnecessary fork.

Sign up to request clarification or add additional context in comments.

9 Comments

or, just eval "$(outputenv --name myprogram) myprogram --options"
No, that won't work. Who wrote outputenv to include semicolons?!
Anyhow, better not to eval the options; who knows when they'll contain potentially-hostile user-provided data?
I don't have to do set -a just can run the eval and it is set for the current session by just adding the end braces.
@vpshastry, if you don't do set -a they're just regular shell variables, not exported as environment variables. And if they're just regular shell variables, myprogram won't be able to see them.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.