Environment Variables — Terminal

NAME=value (no spaces) makes a shell variable, and $NAME is replaced by its value, inside double quotes too, but not inside single quotes. For example…

The same code runs on your laptop and on the server, but the database is different. How does the program know where it is running? From environment variables: NAME=value pairs that a program carries while it runs, such as HOME=/home/budi or APP_ENV=development. Programs read them to learn their settings: whether they run in development (still being built) or production (used by real users), and where the database is.

The way a program receives environment variables is like leaving your child at grandma's house with a photocopy of your list of instructions. The child only brings the instructions you wrote on that list, not everything in your head. And if the child scribbles on the photocopy, your own list doesn't change. Here, you are the shell, the child is the program you run, and the photocopy is the copy of the variables.

Shell variables: make one and read it

A variable is a name that holds a value:

$ NAME=Budi
$ echo "Hello $NAME"
Hello Budi
$ echo 'Hello $NAME'
Hello $NAME
$ NAME = Budi
bash: NAME: command not found

Variable names are usually uppercase with underscores, such as APP_ENV or DB_HOST.

export: hand it to the programs you run

A program that is running is called a process. A program you start from the terminal, such as node app.js (it runs the JavaScript file app.js), is called a child process. Your shell is its parent (the parent process). A child process only gets a copy of the variables that have been exported.

The file app.js holds one line. process.env holds the environment variables that a Node.js program receives, so this line shows the value of APP_ENV:

console.log(process.env.APP_ENV);

Below, APP_ENV gets a value without export, then node app.js runs. Guess first what node app.js shows: development or undefined (no value)?

$ APP_ENV=development
$ echo $APP_ENV
development
$ node app.js
undefined
$ export APP_ENV
$ node app.js
development

Two more rules, still in the same shell (APP_ENV is now exported):

$ APP_ENV=production node app.js
production
$ echo $APP_ENV
development
$ bash -c 'export APP_ENV=staging'
$ echo $APP_ENV
development

The export command and the NAME=value command form exist in bash and zsh, so you can use them on Linux, macOS, WSL and Git Bash. On Windows, PowerShell and Command Prompt (cmd, the older shell that comes with Windows) use other forms. In those two Windows shells, an environment variable you create goes straight to the programs you run, so there is no separate export step:

Shell Set a value Read it
bash, zsh export APP_ENV=development echo $APP_ENV
PowerShell $env:APP_ENV = "development" $env:APP_ENV
cmd set APP_ENV=development echo %APP_ENV%

This difference matters for the scripts in package.json (the settings file of a Node.js project). A script there is a command with a name, and you run it with npm run. On Windows, npm run runs scripts with cmd, so the script "start": "APP_ENV=production node app.js" fails there. Two ways work on every system. One is the cross-env package (a library you install with npm): cross-env APP_ENV=production node app.js. The other is to put the value in a .env file, then run node --env-file=.env app.js (see the .env part below).

Built-in variables, PATH, and making it permanent

Some environment variables are already there when the terminal opens:

$ echo $HOME
/home/budi
$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ which node
/usr/local/bin/node

Every variable you make in the terminal is gone when the terminal closes. To make one permanent, put its export line in ~/.bashrc (bash on Linux) or ~/.zshrc (zsh, the default on macOS). The shell reads that file every time a terminal opens. In a terminal that is already open, run source ~/.bashrc (read it again) or open a new terminal.

The .env file in a project

An app's settings usually live in a .env file in the project folder:

# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME="mydb"

# App
APP_ENV=development
SECRET='s3cret'

Reading .env with JavaScript

In the exercise, you write the function parseEnvFile(content). It turns the contents of the .env file above (one string) into an object (a set of key and value pairs). One way to write it:

function parseEnvFile(content) {
  const result = {};

  for (const rawLine of content.split("\n")) {
    const line = rawLine.trim();
    if (line === "" || line.startsWith("#")) continue; // blank line or comment

    const eq = line.indexOf("=");
    if (eq === -1) continue; // not KEY=VALUE

    const key = line.slice(0, eq).trim();
    let value = line.slice(eq + 1).trim();
    const first = value[0];
    if ((first === '"' || first === "'") && value.endsWith(first)) {
      value = value.slice(1, -1); // drop the wrapping quotes
    }
    result[key] = value;
  }

  return result;
}

What happens to each line of the .env above:

Line What happens Goes into the object
# Database a comment, skipped (nothing)
DB_HOST=localhost cut at the first = DB_HOST: "localhost"
DB_PORT=5432 the value stays text DB_PORT: "5432"
DB_NAME="mydb" double quotes dropped DB_NAME: "mydb"
(blank line) skipped (nothing)
SECRET='s3cret' single quotes dropped SECRET: "s3cret"

With APP_ENV: "development" as well, the object has 5 keys. In the exercise, the result is stored in config, so Object.keys(config).length (the number of keys) is 5.

⚠️ Small slips that break variables

TL;DR: NAME=value (no spaces) makes a shell variable, and $NAME is replaced by its value, inside double quotes too, but not inside single quotes. For example, NAME=Budi; echo "Hello $NAME" prints Hello Budi (the ; separates two commands). A program you run from the shell (a child process) only gets a copy of the variables you export. Without export, process.env.APP_ENV in a Node.js program is undefined (no value). NAME=value command applies to that one command only, and a child process can't change the variables of the shell that started it. PATH is the list of folders the shell searches for programs. To make a variable permanent, put its export line in ~/.bashrc or ~/.zshrc. A .env file is read by the app, not by the shell: one KEY=VALUE per line, # for comments, wrapping quotes dropped, every value text, and never committed to Git.

⚡ Make a shell variable

Write:

NAME=Budi
echo "Hello $NAME"

Meaning: The first line makes a shell variable (a name that holds a value) called NAME with the value Budi. No spaces around =. The shell replaces $NAME with its value before the command runs, so echo prints Hello Budi. Inside single quotes, $NAME isn't replaced.

⚡ export: hand it to child processes

Write:

APP_ENV=development
node app.js
Guess first: node app.js runs app.js, which prints process.env.APP_ENV (the value of APP_ENV the program receives). What appears?

undefined (no value). Without export, the variable only exists in this shell and doesn't go along to the programs you run.

Meaning: export APP_ENV marks the variable to be handed over. After that, a program you run from this shell (a child process) gets a copy. Changes the child process makes don't come back to your shell.

⚡ PATH: where the shell looks for programs

Meaning: PATH is a built-in variable that holds a list of folders separated by :. When you type node, the shell looks for the program node in those folders, starting from the one on the left. To keep a variable after the terminal closes, put its export line in ~/.bashrc (bash on Linux) or ~/.zshrc (zsh): the shell reads that file every time a terminal opens.

⚡ The .env file

Write:

DB_HOST=localhost
DB_PORT=5432
DB_NAME="mydb"

Meaning: A .env file holds an app's settings. One line holds one KEY=VALUE (a name and its value), # marks a comment, and wrapping quotes are dropped. The app reads this file, not the shell. It holds secrets, so never commit it to Git.

In the exercise, comment lines and blank lines must not become keys.

What you will learn