Course contentsShow
← Linux
Lesson 20 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Global vs Local Environment Scope

Define the boundary of exported variables and their accessibility in child processes.

In this lesson, you will learn how the shell creates a boundary between the variables you define for your current session and the variables accessible to the programs you launch.

The Scope Problem

When you type MY_VAR="hello" into your terminal, you are creating a local shell variable. This variable lives only within your current shell process. If you decide to run a program—like a script or a utility—that new program starts as a child process (remember our lessons on Fork-Exec). By default, child processes do not receive copies of your local shell variables. They only inherit the "exported" environment.

Local vs. Global (Exported)

Think of Local variables as private notes on your desk; they are helpful for your own calculations, but they aren't part of the "official record" passed to your assistants (child processes).

To make a variable "Global" (part of the environment), you must export it. When you export a variable, you are telling the shell: "Copy this value into the environment block that will be passed to any child process I create via execve."

Consider this example:

# 1. Local variable
GREETING="Hello"

# 2. Try to print it in a child process
bash -c 'echo $GREETING'  # Output: (nothing)

# 3. Export the variable
export GREETING

# 4. Now the child process sees it
bash -c 'echo $GREETING'  # Output: Hello

The Boundary

The boundary is clear: once the execve system call is made, the child process receives a snapshot of the environment variables provided by the parent. Any local variables are discarded during the exec transition because they were never part of the process's exported environment block. Even if you define a variable globally later, existing child processes cannot "reach back" and grab it. They only know what they were handed at the exact moment they were birthed.

Key Takeaway: Local variables exist only in the current shell, while exported variables are passed down to child processes through the environment block during the execve transition.