Bash: Is it possible to set environment variables for a single sub-process by evaluating a command?

Viewed 376

This works perfectly fine:

>$ ENV=var printenv
ENV=var

This also works but it sets the environment variable for the entire shell:

>$ export $(echo ENV=var)

>$ printenv
ENV=var

I would like to do something like this but it fails:

>$ $(echo ENV=var) printenv
bash: ENV=var: command not found

Is there another way to pass environment variables to a single sub-process by evaluating a command?

1 Answers

Use env.

env "$(echo ENV=var)" printenv

Or use eval but know how to safely use it.

eval "$(echo ENV=var)" printenv 

Either way in both commands you have to make sure the output is sanitized.

Related