Search⌘ K
AI Features

Subshells

Explore subshells in Bash scripting by learning how to create them, understand their variable scope, and distinguish between command grouping methods. This lesson helps you manage scripts efficiently by using subshells for environment isolation and output redirection, enhancing your control over shell behavior.

The concept of subshells is not a complicated one, but can lead to a little confusion at times, and occasionally is very useful.

How Important is this Lesson?

As with process substitution, this is another concept I came to later in my bash career. It comes in handy fairly often, and an understanding of it helps deepen your bash wisdom.

Shell
VAR1='the original variable'
Terminal 1
Terminal
Loading...

Now create a subshell:

Shell
(

You’ll notice the prompt has changed. Now try and echo something:

Shell
echo Inside the subshell

It’s not been run. This is because the subshell’s instructions aren’t run until the parenthesis has been closed. Next we’ll try and echo the variable we created outside.

Shell
echo ${VAR1}

Then update that variable to another value, and echo it again:

Shell
VAR1='the updated variable'
echo ${VAR1}

And finally create another variable, before closing the subshell out:

Shell
VAR2='the second variable'
)

So a subshell is a shell that inherits variables from the parent shell, and whose running is deferred until the parentheses are closed.

It will pay to think about the output and review the subshell commands to grasp what you just saw. Play with the commands and experiment ...