Subshells

To conclude this chapter, we will look at a simple type of interprocess relationship: that of a subshell with its parent shell. We saw in Chapter 3, that whenever you run a shell script, you actually invoke another copy of the shell that is a subprocess of the main, or parent, shell process. Now let’s look at subshells in more detail.

Subshell Inheritance

The most important things you need to know about subshells are what characteristics they get, or inherit, from their parents. These are as follows:

  • The current directory

  • Environment variables

  • Standard input, output, and error, plus any other open file descriptors

  • Signals that are ignored

Just as important are the things that a subshell does not inherit from its parent:

  • Shell variables, except environment variables and those defined in the environment file (usually .bashrc)

  • Handling of signals that are not ignored

We covered some of this in Chapter 3, but these points are common sources of confusion, so they bear repeating.

Nested Subshells

Subshells need not be in separate scripts; you can also start a subshell within the same script (or function) as the parent. You do this in a manner very similar to the command blocks we saw in the last chapter. Just surround some shell code with parentheses (instead of curly brackets), and that code will run in a subshell. We’ll call this a nested subshell.

For example, here is the calculator program from the last chapter, with a subshell instead of a command block:

( while read line; do echo ...

Get Learning the bash Shell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.