In this lesson, you will learn how environment variables flow downward through layers of subshells to maintain consistent configurations across nested process hierarchies.
The Chain of Command
When you run a command in Linux, the shell creates a new process for it. If that command is a script or another shell, it creates its own child processes in turn. An inheritance chain is the path of environment variables as they are copied from parent to child, layer by layer, down this hierarchy.
Think of it like a family tree of information: a parent process passes its "genetic code" (the environment block) to every child it spawns. Each child receives a complete copy of that environment. Because this is a copy, modifications made by a child do not travel back up the chain to the parent, but they are passed down to any grandchildren the child might create.
Visualizing the Hierarchy
Consider this nested structure where we launch a subshell inside another subshell:
export GREETING="Hello"
(
echo "Level 1: $GREETING"
(
export GREETING="World"
echo "Level 2: $GREETING"
)
echo "Level 1 again: $GREETING"
)
In this example:
- The top level exports
GREETINGto the environment. - The first subshell (Level 1) inherits the variable
Hello. - The second subshell (Level 2) inherits that same environment, but then updates its own copy to
World. - When the Level 2 subshell terminates, the process tree returns to Level 1. Because Level 2 only modified its own copy of the environment, the Level 1 shell still sees
Hello.
This one-way street ensures that you can safely customize settings for a specific task (like changing a PATH or a temporary directory) within a nested script without accidentally corrupting the environment of your main, long-running terminal session. As long as you use export, the variables remain part of the inheritance chain for every subsequent process spawned within that specific branch of your process tree.
Key Takeaway: Environment variables are passed as a downward copy-by-value, meaning children inherit their parent's state, but changes made in a child process remain isolated from the parent.