In this lesson, you will learn how to create "sandboxed" environments using subshells so your temporary configuration changes don’t break your main shell session.
The Problem of Global Mutation
When you change an environment variable or set a shell option (like set -e or shopt), that change typically persists for the life of your current shell session. If you are writing a script or running a complex command that requires a unique configuration—like a different PATH or a specific file globbing setting—you might accidentally leave your shell in a state that causes bugs later on. This is where subshells come to the rescue.
The Subshell Sandbox
A subshell is a child process spawned by your current shell to execute a specific command or group of commands. Because this process is a distinct child, any changes you make to variables or shell settings within the subshell are isolated. When the subshell finishes, it exits, and those changes vanish, leaving your parent shell exactly as it was.
To run a command in a subshell, wrap it in parentheses:
# Parent shell has its default configuration
echo "My current directory is $PWD"
(
# Everything here happens in a subshell
cd /tmp
export MY_TEMP_VAR="secret"
echo "Inside subshell: $PWD, $MY_TEMP_VAR"
)
# Back in the parent shell
echo "Back in parent: $PWD, $MY_TEMP_VAR"
In this example, the cd command and the export only affect the subshell. Once the closing parenthesis is reached, the subshell process terminates. When you return to your prompt, you are still in your original directory, and $MY_TEMP_VAR will be empty.
Why This Matters
By using subshells, you prevent "side effects." You can safely modify the environment to suit the needs of a single command without worrying about accidentally altering your shell's global configuration. This keeps your main shell environment clean, predictable, and stable, regardless of how many temporary adjustments you need to perform during your workflow.
Key Takeaway: Wrapping commands in parentheses creates a temporary subshell, ensuring that any environment changes are discarded once the command finishes, thereby protecting your parent shell from unintended configuration drift.