user1934428
user1934428

Reputation: 22311

Set environment variable for subshell invocation

I want to extend the concept to be able to set an environment variable just for the invocation of one subprocess, i.e.

VARIABLE=VALUE COMMAND PARAMETERS

for instance

FOO=6 printenv FOO

to the case, where COMMAND is a subshell. As an example to demonstrate this problem, I used

 FOO=6 BAR=7 ( printenv FOO; printenv BAR )

which resulted in a

zsh: parse error near `('

Why is it that this does not work, although

 export FOO=6
 export BAR=7
 ( printenv FOO; printenv BAR )

does work. Of course I could do a

# Explicit call of zsh needed:
FOO=6 BAR=7 zsh -c 'printenv FOO; printenv BAR'

or a

# Two nested subshells, instead of one, and a lot more to type:
 (export FOO=6; export BAR=7; (printenv FOO; printenv BAR))

but is there also a simple way using notation with parenthesis for the subshell?

I somehow feel that I'm lacking something fundamental in making subshells using (....)

Upvotes: 1

Views: 888

Answers (1)

Arakis
Arakis

Reputation: 899

The simplest approach is to use the export variant within a single subshell. There's no need for a secondary nested subshell.

$ (export FOO=6; export BAR=7; printenv FOO; printenv BAR);
6
7

Upvotes: 1

Related Questions