In this lesson, you will learn how a Bash script interacts with its parent process to inherit, modify, and manage the environment variables that define its execution context.
What is an Execution Context?
When you launch a script, it doesn't start in a vacuum. It is born as a child process of your current shell. By default, the child inherits a copy of the parent’s environment—a collection of variables (like PATH, USER, or custom flags) that tell the script about the system state.
Think of the "Environment" as a backpack the parent hands to the child. The child can look through the backpack and use what's inside, but if the child adds or removes items, the parent’s backpack remains unchanged.
Managing Scope and Inheritance
If you define a variable in your terminal, the script won't see it unless you export it. export tells the shell to include that variable in the environment passed to any future child processes.
Consider this interaction:
# In your terminal (Parent)
MY_VAR="Hello"
./script.sh # The script cannot see MY_VAR
export MY_VAR="Hello"
./script.sh # Now, the script sees the environment variable
Inside script.sh, you can change the variable:
# Inside script.sh
MY_VAR="Changed"
Crucially, when script.sh finishes and returns control to your terminal, MY_VAR in your terminal is still "Hello". The environment modification was strictly scoped to the lifecycle of the child process.
Why This Matters
Managing this context is vital for structured script design. If you want a child process to have specific settings—like a temporary PATH or a custom configuration file path—you can modify the environment just before execution without polluting your main terminal session. This allows you to run multiple processes, each with their own "custom backpack," without them interfering with one another or the parent shell.
Key Takeaway: Child processes inherit an environment snapshot from the parent, but any changes made to variables within the child remain local to that process and do not affect the parent shell.