Local Variables vs. Environment Variables

Su Suriya Ravichandran Updated 06 Dec 2026
4 min read ·Lesson 37 of 205

Bash has two main kinds of variables. A local (or shell) variable lives only inside the shell that created it. An environment variable is also passed to every program the shell starts. Choosing between them decides which parts of your system can see a value.

The word "local" has a second, narrower meaning in Bash: variables declared with the local keyword inside a function. This lesson uses "local variable" for the broad meaning, a variable that stays in the shell, and calls out the function case separately.

The Two Kinds Side by Side

Create one variable of each kind and ask a child process what it can see:

name="local_only"
export SHARED="visible_to_children"

cat > peek.sh <<'EOF'
#!/usr/bin/env bash
echo "peek: name=[${name-unset}] SHARED=[${SHARED-unset}]"
EOF
chmod +x peek.sh
./peek.sh
peek: name=[unset] SHARED=[visible_to_children]

peek.sh runs as a separate process. It received SHARED because the variable was exported, and it could not see name. The expansion ${name-unset} prints the word unset when the variable does not exist, which makes the difference visible.

Asking Bash Which Kind a Variable Is

The declare -p command prints a variable together with its attributes. An exported variable carries the -x attribute:

declare -p name SHARED
declare -- name="local_only"
declare -x SHARED="visible_to_children"

The double dash after declare means "no special attributes", so name is a plain shell variable. The -x on SHARED marks it for export. You can also list only exported names with compgen -e:

compgen -e | grep -x -E 'SHARED|name'
SHARED

The -x option of grep requires an exact whole-line match, which prevents partial matches on longer names. Only SHARED is in the exported list.

What Else Can See a Local Variable

A local variable is not completely hidden. It is visible to code that runs inside the same shell or in a copy of it. The boundary is the creation of a new program, not the use of parentheses or a function.

Subshells

A subshell, created with parentheses, is a copy of the current shell. It sees both kinds of variables:

( echo "subshell: name=[$name] SHARED=[$SHARED]" )
subshell: name=[local_only] SHARED=[visible_to_children]

Changes made inside the subshell are lost when it ends, because the subshell is a copy.

Sourced Files

The source command (or a dot) reads a file and runs its commands in the current shell, so there is no child process. A sourced file sees local variables and its changes are kept:

cat > srcpeek.sh <<'EOF'
echo "sourced: name=[${name-unset}] SHARED=[${SHARED-unset}]"
name="changed_by_source"
EOF

source ./srcpeek.sh
echo "after source name=[$name]"
sourced: name=[local_only] SHARED=[visible_to_children]
after source name=[changed_by_source]

Both variables were visible, and the new value of name stayed after the file finished. Running the same file as ./srcpeek.sh would have started a child process that could not see name.

Functions and the local Keyword

A function runs inside the current shell, so it can read and change any variable. The local keyword is the way to create a variable that exists only for the duration of the function call:

f() { local name="inside_f"; echo "f: $name"; }
f
echo "after f: $name"
f: inside_f
after f: changed_by_source

The function used its own name, which shadowed the shell's variable of the same name while it ran. A later lesson on functions covers this in depth. Note that local is about scope within the shell, while export is about visibility to other programs. The two are independent.

A Child Gets a Snapshot

An exported variable is copied to a child process when the child starts. A later change in the parent does not reach a child that is already running:

export STATE=one
bash -c 'sleep 0.3; echo "late child STATE=$STATE"' &
STATE=two
wait
late child STATE=one

The background child started while STATE was one and waited a moment before printing. Meanwhile the parent changed its own STATE to two. The child still printed one, because it holds a private copy. The & runs the command in the background, and wait makes the shell wait for it to finish. Later lessons explain both.

Switching a Variable Between the Two Kinds

A local variable becomes an environment variable when you export it, as lesson 38 shows. The reverse direction uses export -n, which removes the export attribute but keeps the variable and its value in the current shell:

export -n SHARED
./peek.sh
echo "SHARED still in this shell: [$SHARED]"
export SHARED
peek: name=[unset] SHARED=[unset]
SHARED still in this shell: [visible_to_children]

After export -n, the child no longer received SHARED, but the shell kept using the value. The last line restores the export.

Choosing Between the Two

Use these guidelines when you decide what to do with a new variable:

SituationChoice
A counter, loop index, or temporary result used only in your scriptLocal variable
A value that the script's own functions useLocal variable (or local inside the function)
A setting that a program you start must read, such as TZ, LANG, or a tool's configuration variableEnvironment variable
A value that you want to hand to child scriptsEnvironment variable

Keeping a variable local avoids surprises. Every exported variable is visible to every program the script runs, so exporting only what is needed keeps the environment small and prevents values from leaking into programs that should not have them. The usual naming convention reflects the difference: environment variables and constants in UPPERCASE, ordinary local variables in lowercase.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Local Variables vs. Environment Variables and get answers drawn from it.

Signed-in readers only.