Environment Variables

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 36 of 205

An environment variable is a named piece of text that every running program carries with it. Programs read these values to learn things about the world around them: which user is running them, where to look for other programs, which language to speak, or which database to connect to. Bash uses environment variables constantly, and you will meet them in almost every real script.

What Makes a Variable "Environment"

Every process on a Unix-like system, including each running Bash shell, has an environment. The environment is a list of NAME=value text entries that the operating system hands to the process when it starts. The process can read the list, and when it starts another process, it can pass the list along.

A variable you create in Bash is not in that list by default. Compare an ordinary shell variable with an environment variable using printenv, a program that prints variables from the environment:

city="Chennai"
printenv city
echo "status=$?"

export GREETING="Hello"
printenv GREETING
echo "status=$?"
status=1
Hello
status=0

The first printenv printed nothing and returned status 1, which means "not in the environment". The variable city exists inside Bash, but programs that Bash starts cannot see it. The second variable was marked with export, a built-in command that places a variable into the environment. The next lessons cover export in detail. For now, remember the rule: a variable is an environment variable when it is exported.

How Bash Passes the Environment to Programs

Whenever Bash runs a command, it starts a new process. That child process receives a copy of the exported variables at the moment it starts. A script is a good way to observe this, because a script runs as a child process:

cat > show_child.sh <<'EOF'
#!/usr/bin/env bash
echo "child: city=[${city-unset}] GREETING=[${GREETING-unset}]"
EOF
chmod +x show_child.sh
./show_child.sh
child: city=[unset] GREETING=[Hello]

The notation ${city-unset} expands to the value of city, or to the word unset if the variable does not exist. The child could not see city, because it was never exported, but it received GREETING.

The Copy Travels Down, Never Up

Because the child holds a copy, anything the child does to its variables stays inside the child. The parent shell never sees the change:

export COUNTER=1
cat > bump.sh <<'EOF'
#!/usr/bin/env bash
COUNTER=$((COUNTER + 1))
echo "child COUNTER=$COUNTER"
EOF
chmod +x bump.sh
./bump.sh
echo "parent COUNTER=$COUNTER"
child COUNTER=2
parent COUNTER=1

The child read the inherited value 1, added one, and printed 2. Back in the parent shell the value is still 1. This one-way flow is the most important idea about environments. It explains why a script that sets a variable cannot change your terminal's variables, a point that returns in the lesson on running scripts with source.

Passing Values Through Several Levels

The environment keeps flowing downward as long as each level exports the value. In this chain, script A starts script B:

cat > nested_a.sh <<'EOF'
#!/usr/bin/env bash
echo "a sees LEVEL=$LEVEL"
LEVEL=child_of_a
export LEVEL
bash ./nested_b.sh
echo "a after b: LEVEL=$LEVEL"
EOF
cat > nested_b.sh <<'EOF'
#!/usr/bin/env bash
echo "b sees LEVEL=$LEVEL"
LEVEL=changed_by_b
EOF

export LEVEL=grandparent
bash ./nested_a.sh
a sees LEVEL=grandparent
b sees LEVEL=child_of_a
a after b: LEVEL=child_of_a

Script A inherited grandparent, changed its own copy to child_of_a, and B received that new value. When B changed its copy to changed_by_b, A's copy was not affected.

Viewing the Environment

Several commands list environment variables. They are useful for different jobs:

CommandWhat it shows
printenvEvery variable in the environment, as NAME=value lines
printenv NAMEOnly the value of NAME (exit status 1 if it is not set)
envThe same list as printenv; it can also run a command with a changed environment
export -p or declare -xThe exported variables as Bash declarations
compgen -eOnly the names of exported variables

To look at a few variables from a larger list, combine them with grep. This example creates two variables with a shared prefix and then displays them in each form:

export APP_NAME=demo APP_PORT=8080
printenv | grep '^APP_' | sort
declare -x | grep -E 'APP_(NAME|PORT)'
compgen -e | grep -E '^APP_' | sort
APP_NAME=demo
APP_PORT=8080
declare -x APP_NAME="demo"
declare -x APP_PORT="8080"
APP_NAME
APP_PORT

printenv takes several names at once and prints only the values, in the order you asked for them:

export Z_ONE=1 Z_TWO=2
printenv Z_ONE Z_TWO
1
2

The output of a bare printenv is long on a real system, so it is almost always filtered or paged. The exact variables differ from one machine to the next.

Setting a Variable for One Command Only

You often want a value to exist for a single program run without leaving it in your shell. Bash supports this by writing assignments in front of the command, on the same line:

TZ=Asia/Kolkata date +%Z
TZ=UTC date +%Z
echo "TZ after: [${TZ-unset}]"
IST
UTC
TZ after: [unset]

TZ is the time zone variable that date reads. Each date command received its own TZ and printed a different zone abbreviation. After the two lines finished, the variable was gone from the shell. A prefix assignment works like a temporary export that lasts for one command.

The env command does the same thing and also works with commands that Bash does not parse as simple commands:

env APP_MODE=test bash -c 'echo "inner APP_MODE=$APP_MODE"'
echo "outer APP_MODE=[${APP_MODE-unset}]"
inner APP_MODE=test
outer APP_MODE=[unset]

The command bash -c '...' starts a new Bash that runs the text in quotes. Because the text is in single quotes, the inner shell, not the outer one, expands $APP_MODE, and it finds the value that env supplied.

Starting with an Empty Environment

The -i option of env ignores the inherited environment completely and starts the command with only the variables you list:

env -i FOO=bar /usr/bin/env
FOO=bar

The inner env program found exactly one variable. This technique is handy when you need to test whether a script depends on a variable that happens to exist on your own machine.

How Programs Read the Environment

Environment variables are not a Bash feature. They belong to the operating system, and every programming language can read them. In Python, the os.environ mapping holds the environment of the running process:

export GREETING="Hello"
python3 -c 'import os; print(os.environ.get("GREETING"), os.environ.get("city"))'
Hello None

Python found the exported GREETING and returned None for city, which was never exported. Because of this, environment variables are the standard way to hand configuration from a shell script to the programs it starts.

Using an Environment Variable as a Setting

A common real-world pattern lets a script behave differently depending on a variable, with a fallback when the variable is missing. The expansion ${NAME:-default} yields the value of NAME, or default if NAME is unset or empty:

cat > deploy.sh <<'EOF'
#!/usr/bin/env bash
env_name="${APP_ENV:-development}"
echo "Deploying in $env_name mode"
if [[ $env_name == production ]]; then
  echo "Extra checks enabled"
fi
EOF
chmod +x deploy.sh

./deploy.sh
APP_ENV=production ./deploy.sh
echo "APP_ENV in this shell: [${APP_ENV-unset}]"
export APP_ENV=staging
./deploy.sh
Deploying in development mode
Deploying in production mode
Extra checks enabled
APP_ENV in this shell: [unset]
Deploying in staging mode

The first run found no APP_ENV and used the default. The second run supplied the value only for that command. The last run used a value exported earlier in the shell, so every program started afterward sees staging.

Facts About the Values

  • Every value is text. A variable that looks like a number, such as PORT=8080, is stored as the characters 8080. Bash converts it to a number only when you ask, for example inside $(( )).
  • Values may contain spaces. Quote them when you assign, as in export FULL_NAME="Ana Maria", and quote them again when you use them. printenv FULL_NAME prints Ana Maria.
  • An exported variable can be empty. export EMPTY= puts a variable with an empty value into the environment, and printenv EMPTY prints an empty line and returns status 0. This differs from a variable that is not set at all, where printenv prints nothing and returns status 1.
  • Names in the environment are only text. The operating system does not care what a name looks like, so env 'my-var=5' printenv 'my-var' prints 5. Bash cannot assign such a name itself, as the lesson on naming rules showed, which is why the lowercase and underscore style is the safe choice.

Where the Starting Environment Comes From

When you open a terminal, your shell already has a long list of variables, such as HOME, PATH, SHELL, and LANG. They were put there by earlier programs: the login process, the desktop session, and the startup files that Bash reads (later lessons cover files such as .bashrc and .bash_profile). Each layer passes its environment down to the next. Whatever your terminal starts, including every script you run, inherits this environment unless you change it.

Because the environment is visible to every child process and often to tools that record process information, it is not a secure place for passwords. The lesson on handling secrets returns to this point.

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 Environment Variables and get answers drawn from it.

Signed-in readers only.