Course contentsShow
← Linux
Lesson 251 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Subshell vs Execution State

Understand the exact state preserved across process boundaries.

In this lesson, you will learn why variables created inside a subshell vanish the moment that subshell completes, while changes in the main shell persist.

When you run a command in a shell, you are working within a specific Execution State. This state includes your current environment variables, shell options, and the values assigned to your variables. However, when you use parentheses () to create a subshell, the operating system performs a fork. This creates an exact copy of your current shell's process to execute the commands inside the brackets.

Because a subshell is a separate process, it receives its own copy of the environment. Think of it as a photocopy of a document: if you write notes on the photocopy, the original document sitting on your desk remains unchanged.

Consider this example:

# Set a variable in the main shell
MY_VAR="Original"

# Modify it inside a subshell
(
  MY_VAR="Changed"
  echo "Inside subshell: $MY_VAR"
)

# Check the value in the main shell
echo "Outside subshell: $MY_VAR"

When you run this, the output will show Inside subshell: Changed, followed by Outside subshell: Original.

The subshell had the authority to modify its local copy of MY_VAR, but it had no way to "reach back" and alter the memory or environment of its parent process. Once the subshell finishes, its memory is reclaimed by the system, and any modifications it made are discarded. This is a critical security and stability feature: it prevents temporary tasks or complex pipelines from accidentally corrupting the variables and settings that your main script relies upon.

If you ever need to perform a task without affecting your main shell's configuration, the subshell is your safest tool. If you need the changes to persist, you must perform the operation within the main execution state instead.

Key Takeaway: A subshell is a temporary environment; changes made to variables inside it are discarded upon exit, leaving the parent process’s execution state entirely undisturbed.