Advanced

Environment variables

The environment is a set of named strings every program starts with. It is how configuration reaches a program without arguments, and it is also why the same command behaves differently on two machines. Reading it is how you find out which one you are on.

What you will see

Empty - the assignment never reached your shell, which is the scoping that keeps state from drifting.

About 1 min of reading

Try It

Scope a variable to one command.

1

Set for one run

GREETING=hello node -e 'console.log(process.env.GREETING)'

Before you run it, say out loud what it will print. Then open the answer.

What it prints
hello - set only for that command.
2

Prove it did not leak

echo "$GREETING"

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Empty - the assignment never reached your shell, which is the scoping that keeps state from drifting.

Data Flow

Named values reach a program at start.
1 The shell holds the environment
↓
2 export sends it to children
↓
3 The program reads the values
↓
4 Behaviour follows the values
Why this works
Secrets in the environment

Configuration that differs per machine goes in the environment, not in a file in the repository. A secret committed to a file is visible to every reader of the repository, and the environment is the ordinary place it belongs.

A missing variable is a crash

A program that expects a variable and gets nothing usually fails with a message that names the variable. That failure is the design working; the fix is to set it, not to change the program.

Examples

Read one value

echo "$PATH" prints a value that decides where programs are found. Printing a variable before using it is the fastest way to see what a program will actually do.

Set it for one command

PORT=3000 node server.js sets the variable for that one run only. That scoping is the clean way to change behaviour without leaving the shell in a state you forgot about.

export reaches children

A plain assignment is local to the shell; export sends it to programs the shell starts. The difference explains why a variable you set works on the terminal and not inside a script.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Exit status and failure
Previous Lesson
Exit status and failure
Next Lesson
A script that runs anywhere
A script that runs anywhere →