0

Let's say I want to run the process foo with different variables set, like:

FOO=1 foo
FOO=2 foo
FOO=1 BAR=7 foo

How can do do this without repeating the foo command repeatedly? E.g., by looping over the environment to set, like:

for e in 'FOO=1' 'FOO=2' 'FOO=1 BAR=7'; do
  env "$e" foo
done

That almost works, except in the case with $e equal to FOO=1 BAR=1, FOO gets set to 1 BAR=1 and BAR doesn't get set at all because env sees a single argument. I could use env $e, i.e., without quoting e - but then it doesn't work if the variable values have spaces.

1

You are not going to get much shorter. If the issue is that the command you want to run is long, you might write a helper function, e.g.

r(){ env "$@" foo with lots of args ; }
r FOO=1
r FOO=2
r FOO=1 BAR=7
r FOO='1 BAR=7'

If there is a character you know is not going to be in either the names or the values of the environment variables you could use this to split, or you can attempt to quote the values correctly and use eval.

The question is why do you want to do this?

  • The question is why do you want to do this? To avoiding the repeating the foo command (which is much more complex than just foo). Also to allow the possibility of having tested loops, e.g. 5 possible environments in one list, and 3 in another, and then nested loops to try all 5*3=15 combinations. – BeeOnRope Jun 23 '19 at 2:22
  • For the repeating the foo command (which is much more complex than just foo) case, the helper function is perfect. For nested loops it is perfectly possible to have one helper function for each level of nesting, so for a 3 way you could have f1(){ r X=1; r X=2 ; r X=3 ; }, and for the 15 way f2(){ env Y=1 f1; env Y=2 f1 ; env Y=3 f1 ; env Y=4 f1 ; env Y=4 f1 ; }. In most cases you do not need to use the env program. – icarus Jun 23 '19 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.