A Quick Introduction to Unix/Shells and subshells

Shells and subshells
When we open a terminal session a shell will be started for us. That is why we have a prompt visible in our terminal window.

Within a shell we can open another shell - a subshell - by invoking the shell program file or executable. Imagine for example that you have a shell open, the plain vanilla shell sh. You see this: At the prompt in this shell, I can invoke a new subshell. I can invoke bash shell with the command bash. The new shell can be closed down with the command exit. If I invoke a bash subshell I will see something like:



And if I close this shell with exit I see:



Shells contain processes and variables
A shell provides
 * a prompt for the user to communicate by starting, managing, interacting with and ending processes
 * a container for processes and variables

When you invoke a subshell, any processes started in that shell are contained within it. Any data items that are created die with the shell unless they are committed to some persistent storage - perhaps written to a file on a hard drive or exported from the parent shell to new shells. Exporting is not covered here: we assume for now that variables die in the shell they are created in.

To make this more concrete, consider this sequence. We start from any shell in a terminal session and create a shell variable, like this

$ MYVARIABLE="This is the original shell"

To check the contents we can use echo and we prefix the variable name with $, like this:

$ echo $MYVARIABLE

Now we invoke a subshell. We will use the bash shell. Like this

$ bash

This starts a new bash subshell which we can see from the changed prompt, and in the subshell we create a shell variable like this

bash% MYVARIABLE="This is the subshell. When it closes, this variable is destroyed!"

To check the contents of this variable we use echo exactly as before:

bash% echo $MYVARIABLE

Before going further, make sure you know what this will display.

Now, if we exit, the bash subshell closes and we return to our original shell. Work out what the result of typing

$ echo $MYVARIABLE

would be.