7

When I do

Hello=123 npm run a && npm run b && npm run c

I was expecting Hello=123 environment variable to be passed inside a, b and c process. But it turns out only a has the environment variable correctly set.

Is there any other ways that I can pass parameters all at once?

Will Barnwell
  • 4,049
  • 21
  • 34
Shih-Min Lee
  • 9,350
  • 7
  • 37
  • 67
  • 1
    Which shell are you using? The answer might depend on that. – pcarter Aug 31 '17 at 19:56
  • Possible duplicate of [Setting an environment variable before a command in bash not working for second command in a pipe](https://stackoverflow.com/questions/10856129/setting-an-environment-variable-before-a-command-in-bash-not-working-for-second) – Will Barnwell Aug 31 '17 at 20:29

2 Answers2

9

Try:

Hello=123 sh -c 'npm run a && npm run b && npm run c'

Better: use env before the whole line. This makes the one-liner work in both Bourne/POSIX and csh-derived shells:

env Hello=123 sh -c 'npm run a && npm run b && npm run c'

Your observation is that var=val foo && bar sets $var only in the environment of foo, not bar. That's correct. The solution is to set the environment for a command that in turn runs foo and bar: sh -c.

The other solution, of course, is simply:

Hello=123; export Hello   # or export Hello=123 if using bash
npm run a && npm run b && npm run c
dgc
  • 555
  • 3
  • 7
  • 1
    The last solution is cleanest, and if you want it even more clean, wrap it in parentheses so the exported variable is available only where it needs to be. – ghoti Sep 01 '17 at 05:47
  • The first one can work. The last one `Hello=123` pollutes my environment though. – Shih-Min Lee Sep 01 '17 at 11:30
  • Agreed, I don't like the env clutter either. But the previous comment about wrapping in parentheses solves that. – dgc Sep 01 '17 at 19:57
0

I simply use export.

export FOO=bar && npm run a && npm run b && npm run c
wintercounter
  • 7,500
  • 6
  • 32
  • 46