Shell – Set environment variable for subshell

ashenvironment-variablessubshell

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:

FOO=bar sh -c 'first && second'

This sets the FOO environment variable for the single sh command.

To set multiple environment variables:

FOO=bar BAZ=quux sh -c 'first && second'

Another way to do this is to create the variable and export it inside a subshell. Doing the export inside the subshell ensures that the outer shell does not get the variable in its environment:

( export FOO=bar; first && second )

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. If first and second are external utilities (or scripts) that look at their environment, they would not see the FOO variable without the export.

Related Question