Monday, January 31, 2022

[SOLVED] Pass environment variable to multiple commands

Issue

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?


Solution

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


Answered By - dgc
Answer Checked By - David Marino (WPSolving Volunteer)