Variables and the environment

Beginner · 8 min

Shell variables versus environment variables, how export hands a value to child processes, and the one-shot VAR=value command form.

Before thisStartup files and login vs interactive shellsQuoting - single, double and escapes

anthonywritescode · 8 min

Variables and the environment

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by anthonywritescodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A plain assignment `name=value` creates a shell variable that only the current shell can see. There must be no spaces around the equals sign.
  • `export name` marks the variable so every child process inherits a copy. The environment is that set of exported variables.
  • Children get copies. A child changing its copy never changes the parent's variable.
  • `NAME=value command` puts the variable in that one command's environment and leaves the shell untouched.
  • `unset` removes a variable, and `readonly` makes it impossible to change. Variables hold strings, so `n=5+1` is just the text `5+1`.

Two kinds of variable

A shell needs somewhere to keep values: a filename you keep reusing, a count, the directory you started in. That’s a variable. The part that surprises people is that there are two scopes, and they are not the same thing.

A plain assignment creates a shell variable. Only this shell process knows about it. Programs you launch from it never see it. An environment variable is a shell variable that has been marked for export, so every program the shell launches gets a copy.

I tested it with a child Bash process standing in for any program:

$ greeting=hello
$ echo "$greeting"
hello
$ bash -c 'echo "child sees: [$greeting]"'
child sees: []
$ export greeting
$ bash -c 'echo "child sees: [$greeting]"'
child sees: [hello]

Same variable, same shell. The only change was export. The environment is a block of name/value strings the operating system passes to each new process. That is why environment variables work across languages: Python, git and curl all read the same block.

The child gets a copy. If it changes its copy, the parent’s value stays put:

$ bash -c 'greeting=changed; echo "child set it to $greeting"'; echo "parent still has $greeting"
child set it to changed
parent still has hello

This explains a classic confusion. A script that does export PATH=/opt/tools:$PATH can’t change your PATH, because it ran in a child. If you want a script’s assignments to affect your shell, run it with source script.sh (or . script.sh), which executes the lines in your current shell.

Setting a variable for one command

Often you want a variable for exactly one program. Put the assignment in front of the command:

$ GREETING=hi bash -c 'echo "child sees $GREETING"'; echo "parent: [${GREETING-unset}]"
child sees hi
parent: [unset]

The variable lives in that command’s environment and nowhere else. This is how you write TZ=UTC date or LC_ALL=C sort file. Prefer it to export when the value is for a single command, because it can’t leak into later ones.

Seeing and removing variables

$ env | grep -c '^greeting='
1
$ printenv greeting
hello
$ declare -p greeting
declare -x greeting="hello"

env and printenv list the environment, meaning exported variables only. declare -p shows how Bash itself sees one, and the -x flag in its output means “exported”. Without arguments, set lists every shell variable and function, which is a long list.

$ unset greeting; echo "after unset: [${greeting-unset}]"
after unset: [unset]

unset removes it entirely. That is different from greeting=, which leaves a variable that exists and is empty. The ${var-default} form used above tells the two apart, and the parameter expansion lesson covers it properly.

Assigning and exporting in one step

You can export at the moment of assignment, and take the mark off again with -n:

$ export API_HOST=example.test
$ bash -c 'echo "$API_HOST"'
example.test
$ export -n API_HOST
$ bash -c 'echo "[$API_HOST]"'; echo "$API_HOST"
[]
example.test

export -n un-exports: the child loses the variable, and the shell keeps its own copy. That is the cleanest way to see the two scopes are separate flags on one name. I got the same results from macOS’s /bin/bash 3.2 as from Bash 5.3.

Rules that bite

Spaces around = are an error, because Bash then sees a command called greeting:

$ greeting = hello
bash: greeting: command not found

That message is how Bash prints it in an interactive session. My driver script added a line number I trimmed from the output.

Variables hold strings, not numbers. Using + does nothing arithmetic:

$ n=5; n=$n+1; echo "$n"
5+1

Arithmetic needs $(( )), in the arithmetic substitution lesson. And readonly locks a value:

$ readonly LIMIT=10
$ LIMIT=20
bash: LIMIT: readonly variable

Names use letters, digits and underscores and can’t start with a digit. By convention, exported and constant names are UPPER_CASE and your own working variables are lower_case, which keeps you from overwriting something like PATH or USER by accident.

One variable worth knowing: SHLVL counts how deeply nested your shells are. It printed 1 in my shell and 2 in the bash -c child. A few others, such as HOME, PWD and PATH, are set for you; the PATH lesson covers the last.

About the video

“shell vs environment variables (and env, export, etc.)” is anthonywritescode’s episode 547, 7 minutes 39 seconds, published in July 2023. I couldn’t read a transcript. The description says it covers environment variables, shell variables, and shorthands for setting and unsetting them, which matches the material above. It is in English. A shorter You Suck at Programming video on the same topic is linked as a second view.

Where this fits

You can now create and export values. The next lesson is about transforming them without leaving the shell: parameter expansion.

Check yourself

  1. 01You run `token=abc` and then a script that reads `$token`. The script sees nothing. Why?

    The variable was never exported, so it is a shell variable and child processes don't inherit it. Run `export token` or `token=abc ./script`.

  2. 02A script exports `PATH=/tmp:$PATH` and exits. Does your interactive shell's `PATH` change?

    No. The script is a child process with its own copy of the environment. Only commands run in your current shell, such as `source`, can change your shell's variables.

  3. 03What does `LOG_LEVEL=debug ./run.sh` do that `export LOG_LEVEL=debug` doesn't?

    It sets the variable only for that one command. Afterwards the shell has no `LOG_LEVEL`, so nothing leaks into later commands.

  4. 04Why does `greeting = hello` fail?

    With spaces, Bash reads `greeting` as a command name and `=` and `hello` as its arguments. Assignments must be written `greeting=hello` with no spaces.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark