Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable to multiple commands

Tags:

shell

unix

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?

like image 556
Shih-Min Lee Avatar asked Aug 31 '17 19:08

Shih-Min Lee


People also ask

Can we set multiple environment variables?

The set of environment names and the method for altering the environment list are implementation-defined. Depending on the implementation, multiple environment variables with the same name may be allowed and can cause unexpected results if a program cannot consistently choose the same value.

How do I pass an environment variable in bash script?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

What is Setenv in Linux?

setenv is a built-in function of the C shell (csh). It is used to define the value of environment variables. If setenv is given no arguments, it displays all environment variables and their values. If only VAR is specified, it sets an environment variable of that name to an empty (null) value.


1 Answers

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
like image 64
dgc Avatar answered Nov 15 '22 09:11

dgc