Set environment variable for subshell

19,625

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.

Share:
19,625

Related videos on Youtube

AndreKR
Author by

AndreKR

Updated on September 18, 2022

Comments

  • AndreKR
    AndreKR almost 2 years

    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.

  • Kusalananda
    Kusalananda over 5 years
    You can't really compare a function with a subshell, as setting a variable in a function will make it available in the calling environment whereas setting a variable in a subshell would not.
  • Kemin Zhou
    Kemin Zhou over 5 years
    Yes, your are right. Only when you use local inside the function then you can hide it. This is the tricky part of shell programing, inside function you can trump some global variable. I tried to stick to the principle of adding local to variable inside function. I think this feature is only available in bash not in Bourne.
  • Kusalananda
    Kusalananda over 5 years
    You could write the function with func () (...) instead of with func () {...} which would make it run in a subshell... But that would be because of the actual subshell and not because it was a function.