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.
Now create a subshell:
You’ll notice the prompt has changed. Now try and echo something:
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.
Then update that variable to another value, and echo it again:
And finally create another variable, before closing the subshell out:
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 ...