I know that I can run a command with an environment variable like this:
FOO=bar mycommand
I know that I can run commands in a subshell like this:
(firstcommand && secondcommand)
But can I somehow combine those two?
FOO=bar (firstcommand && secondcommand)
gives:
sh: syntax error: unexpected "("
at least in busybox shell (ash).
Edit: Kusalananda suggested FOO=bar sh -c 'first && second'
which is indeed a solution. However, I am also interested in alternative answers because I like the subshell syntax because it doesn't require fiddling around with escaping of quotes.
Best Answer
One way:
This sets the
FOO
environment variable for the singlesh
command.To set multiple environment variables:
Another way to do this is to create the variable and
export
it inside a subshell. Doing theexport
inside the subshell ensures that the outer shell does not get the variable in its environment:Summarizing the (now deleted) comments: The
export
is needed to create an environment variable (as opposed to a shell variable). The thing with environment variables is that they get inherited by child processes. Iffirst
andsecond
are external utilities (or scripts) that look at their environment, they would not see theFOO
variable without theexport
.