Environment Variables
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:
| Command | What it shows |
|---|---|
printenv | Every variable in the environment, as NAME=value lines |
printenv NAME | Only the value of NAME (exit status 1 if it is not set) |
env | The same list as printenv; it can also run a command with a changed environment |
export -p or declare -x | The exported variables as Bash declarations |
compgen -e | Only 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 characters8080. 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_NAMEprintsAna Maria. - An exported variable can be empty.
export EMPTY=puts a variable with an empty value into the environment, andprintenv EMPTYprints an empty line and returns status 0. This differs from a variable that is not set at all, whereprintenvprints 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'prints5. 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.