Subshells





Subshells

Subshells are generated whenever you enclose commands in ()'s, perform command substitution, for background processes, and for co-processes (discussed later in Chapter 8). A subshell is a separate copy of the parent shell, so variables, functions, and aliases from the parent shell are available to the subshell. However, subshells cannot change the value of parent shell variables, functions, or aliases. So if we set LOCALVAR to a value in the current shell:

$ LOCALVAR="This is the original value" 

then check the value in a subshell, we see that it is defined:

$ (print $LOCALVAR) 
This is the original value 

If we set it in the subshell to another value:

$ (LOCALVAR="This is the new value") 

then check the value in the parent shell, we see that LOCALVAR is still set to the original value:

$ print $LOCALVAR 
This is the original value 

By default, things like variables, aliases, and functions from the current environment are not available to separate invocations of the Korn shell unless explicitly exported or exported in the environment file. For example, variables are exported with the typeset –x command. Let's look at LOCALVAR again. It wasn't exported, so if we start a new Korn shell, LOCALVAR is not defined:

$ ksh 
$ print $LOCALVAR 
$ exit 

Once exported, it is available to the new Korn shell:

$ typeset —x LOCALVAR 
$ ksh 
$ print $LOCALVAR 
This is the original value 

As with subshells, environment settings are not passed back to the parent Korn shell. If LOCALVAR is set to another value in the separate Korn shell:

$ LOCALVAR="This is the new value" 

then we exit back to the parent shell, we see that LOCALVAR is still set to the original value:

$ exit 
$ print $LOCALVAR 
This is the original value 

If the allexport option is enabled (set –a, or set –o allexport), variables are automatically exported when defined. By default, this option is disabled.

Aliases can also be exported to separate Korn shells with the alias –x command. If we wanted to use the l alias in a separate Korn shell, it would have to be exported like this:

$ alias —x l 


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows