Appearance
2.9.3 — Environment Variables & the Registry
A developer installs a new command-line tool for the photo-upload service's build. The installer says "done". They type the tool's name in the terminal they already had open, and get "not recognized as a command". They open a new terminal, type it again, and it works.
Nothing was wrong with the installer. The old terminal simply had an old copy of its environment, and the explanation runs straight back to how processes are created (2.2.2). This page explains environment variables on every system, Windows's two kinds of them, and the other place Windows keeps settings: the registry.
1. Environment variables: configuration from the outside
An environment variable is a named piece of text that a process carries with it, such as NODE_ENV=production or PATH=/usr/bin:/bin. Every process has its own set, called its environment. Programs read them for configuration:
PATHlists the folders to search for commands (2.8.1).HOMEon Unix, orUSERPROFILEon Windows, names the user's home folder.TEMPorTMPDIRnames the folder for temporary files.- Programs define their own, such as
NODE_ENV,DATABASE_URLorPORT.
In TypeScript they are in process.env. The upload service might read process.env.PORT ?? "8080" to choose its port. Environment variables are the standard way to configure a program without changing its code, which is why platforms that run containers pass configuration this way, and why one built image can run as development, testing and production with only its environment different.
The rule that explains everything: copied at birth
When a process starts a child, the child receives a copy of the parent's environment, and that copy is fixed at that moment. After that, the two are independent. Changing a variable in the parent does not change the child's copy, and changing it in the child does not change the parent's.
So in the opening story:
- The terminal was started yesterday, with yesterday's
PATH. - Today the installer added the tool's folder to the saved, system-wide
PATHsetting. - But the open terminal still holds its own copy from yesterday. Every command it starts inherits that old copy.
- A new terminal is started from the desktop, which has picked up the updated setting, so it gets the new
PATH.
Figure 1 follows the copies.
PATH in the registry. ② The desktop re-reads it. ③ A terminal opened now copies the new PATH. The terminal opened yesterday still holds its old copy, and so does every command it starts.The dashed arrow happened yesterday, before any of the numbered steps, and it can never be repeated for that terminal. A copy, once made, does not follow the original. That is the whole story: nothing was broken, the old terminal simply holds an old copy.
That one rule, "the environment is copied when a process starts", also explains why export inside a script does not change the shell that ran the script: the script ran in a child process, and its changes died with it. To change the current shell's environment, you must run the script inside the shell with source script.sh.
2. Two scopes on Windows: system and user
On Unix, the environment for a login is built up by the shell from files: system-wide settings in /etc/environment and /etc/profile, then the user's own ~/.profile or ~/.bashrc. Windows has the same idea, with two official scopes and a settings window to edit them.
- System environment variables apply to every user on the machine. Setting one needs administrator rights.
- User environment variables apply only to your own account.
When Windows starts a program for you, it builds the environment from both. For most variables, a user value with the same name wins over the system value. PATH is special: Windows joins the two, system PATH first and then user PATH, so you get the folders from both.
Both scopes are stored in the registry (section 3), and here is the upload service reading them.
ts
// where-path-comes-from.ts — the process's PATH, and the two registry values it was built from
import { execFileSync } from "node:child_process";
import { delimiter } from "node:path";
const mine = (process.env.PATH ?? "").split(delimiter); // (1)
console.log(`this process's PATH has ${mine.length} folders`);
function readPath(key: string): string[] { // (2)
const out = execFileSync("reg", ["query", key, "/v", "Path"], { encoding: "utf8" });
const value = out.split(/\r?\n/).find((l) => /\sPath\s/.test(l))!.split(/REG_(?:EXPAND_)?SZ\s+/)[1];
return value.split(";").filter(Boolean);
}
const system = readPath("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); // (3)
const user = readPath("HKCU\\Environment"); // (4)
console.log(`system PATH (all users): ${system.length} folders`);
console.log(`user PATH (just me): ${user.length} folders`);
const placeholders = [...system, ...user].filter((e) => e.includes("%")).length; // (5)
console.log(`entries stored with %NAME% placeholders: ${placeholders}`);
// Printed on a Windows laptop:
// this process's PATH has 49 folders
// system PATH (all users): 23 folders
// user PATH (just me): 14 folders
// entries stored with %NAME% placeholders: 10(1)process.env.PATHis this process's own copy.path.delimiteris;on Windows and:elsewhere (2.9.1).(2)reg queryis Windows's command-line tool for reading the registry. We run it directly, without a shell, and pick thePathline out of its output.(3)The system-wide variables live under this registry key, on the machine side.(4)The user's own variables live underHKCU\Environment, on the user side.(5)Some entries are stored with placeholders such as%USERPROFILE%\AppData\Local\Microsoft\WindowsApps. They are filled in, expanded, when the environment is built for a new process, so the same setting works for every user name.
Notice the first line. This process had 49 folders, more than 23 + 14. It was started from a terminal program that added folders of its own before starting it. That is the inheritance chain again: every process's environment is whatever its parent handed it, which may differ from the saved settings.
What this means in practice
- "Install for all users" puts a tool's folder in the system
PATH. "Install just for me" puts it in your userPATH. - After changing either one, open a new terminal, and sometimes restart programs such as your editor, which keep their own copy.
- Two tools of the same name in different
PATHfolders: the one in the folder listed first wins.where nodeon Windows, orwhich nodeon Unix, shows which one you will get. - Do not put secrets in environment variables lightly: 2.8.3 showed how easily they can be read.
3. The registry: one database for settings
Unix keeps settings in plain text files scattered across the file system: system settings in /etc, each program's user settings in small hidden files in the home folder, such as ~/.gitconfig. You can read them with any editor, search them with grep and keep them in Git.
Windows took the opposite approach. Almost all system and program settings live in one central, structured database called the Registry. It holds which program opens which kind of file, every installed program's details, hardware and driver settings, services (2.8.4 covers the Linux equivalent), and each user's preferences, including the environment variables from section 2.
Its shape: hives, keys and values
The registry is a tree, much like a file system.
- Keys are like folders. They can hold other keys.
- Values are like files. Each has a name, a type and some data.
- At the top are a few root keys. The two that matter most are
HKEY_LOCAL_MACHINE, writtenHKLM, for the whole machine, andHKEY_CURRENT_USER, writtenHKCU, for the user who is logged in. That is the system-and-user split from section 2 again.
Figure 2 shows one small branch of that tree: the two places that hold the PATH from section 2.
PATH lives under HKLM, several keys deep. The user's own PATH lives under HKCU, in a key called Environment. Both values have the type REG_EXPAND_SZ, so their %NAME% placeholders are filled in when a process starts.Follow each row from left to right, the way a path in a file system reads. A root key, then one or more keys inside it, then a named value with a type and some data. These are exactly the two keys the TypeScript example in section 2 asked reg query to read.
Values are typed, which plain text files are not:
| Type | Holds | Example |
|---|---|---|
REG_SZ | text | a program's install folder |
REG_EXPAND_SZ | text with %NAME% placeholders | PATH entries |
REG_DWORD | a 32-bit number | an on/off setting, 0 or 1 |
REG_MULTI_SZ | a list of texts | a list of server names |
REG_BINARY | raw bytes | hardware data |
Underneath, the registry is stored in a few files called hives. The machine's settings are in files such as SYSTEM and SOFTWARE in the folder C:\Windows\System32\config, and each user's settings are in a file called NTUSER.DAT in their profile folder. Windows loads them when it starts, or when the user logs in, and writes changes back carefully, with its own logging so a crash does not corrupt them, the same idea as the journal in 2.6.2.
You can browse it with the regedit program, read and write it with reg, as the example did, or treat it like a drive in PowerShell: Get-ItemProperty HKCU:\Environment lists your user environment variables as an object (2.9.2).
The trade-off: one central store, or many plain files
Neither design is simply better. Each gives up something to get something.
| Registry | Plain text files | |
|---|---|---|
| Finding a setting | one place, one interface | many files, many formats |
| Types and validation | built in | none |
| Machine and user scopes | built in | by convention |
| Reading by eye, searching | needs tools | any editor, grep |
| Keeping in version control | awkward | natural |
| If it is damaged | can affect the whole system | affects one program |
| Left-over clutter | uninstalled programs leave keys | stray files |
The registry gives every program one consistent, fast, typed store, with machine and user scopes for free. Plain files are transparent, easy to back up, compare and keep in Git, and a broken file only breaks one program. You will see this same tension again and again in system design: one central structured store against many small, independent pieces, as in a single shared database against each service keeping its own data (Part 10). Recognising the shape of the trade-off is more useful than picking a winner.
What the interviewer will push on
"What is the difference between system and user environment variables on Windows?" System variables apply to every user and need administrator rights; user variables apply only to one account. A new process gets both, with user values winning for the same name, except that PATH is joined, system first. Both are stored in the registry. ⚑What are system vs user account environment variables and what difference do they make? [EQ-64]
"Why does a newly installed command only work in a new terminal?" Because every process gets a copy of its parent's environment when it starts, and the old terminal's copy predates the change. The strong answer adds the Unix version of the same fact: export in a script does not affect the shell that ran it, which is why source exists.
"What is the Windows registry?" A central, hierarchical, typed database of system and program settings: keys, typed values, root keys such as HKLM and HKCU, stored in hive files. Contrast it with Unix's plain text configuration files and name the trade-offs.
"Why configure applications with environment variables at all?" They configure a program from outside without changing its code, so one build can run anywhere, which is the basis of how containers and cloud platforms pass configuration. Mention the caution about secrets.
Something to volunteer that nobody asks for: PATH entries in the registry are often stored with placeholders such as %USERPROFILE%, as type REG_EXPAND_SZ, and filled in only when a process's environment is built. That is why the same setting works for every user, and why editing it with the wrong type can quietly break it.
Recall
- An environment variable is named text carried by a process, read for configuration (
PATH,HOME,NODE_ENV,PORT). It configures a program without changing its code. - A child gets a copy of its parent's environment at start, after which they are independent. That is why a new terminal is needed after installing a tool, and why a script's
exportdoes not reach its parent shell. - Windows has system environment variables (all users, admin needed) and user environment variables (one account). User values win for the same name, but
PATHis joined, system first. Placeholders such as%USERPROFILE%are expanded when a process starts. - The Registry is Windows's central, typed settings database: keys, typed values (
REG_SZ,REG_EXPAND_SZ,REG_DWORD), root keysHKLMandHKCU, stored in hives such asSYSTEMandNTUSER.DAT. - Registry versus Unix text files: one consistent typed store versus transparent, versionable, independent files; the same central-versus-distributed trade-off recurs across system design.
Self-test: Walk through why the new tool worked in a new terminal but not the old one. Why did the demo's process have more PATH entries than system and user together? What does REG_EXPAND_SZ add over REG_SZ? Where are the registry's machine and user settings stored on disk? Give one advantage of each side of the registry-versus-files trade-off.
Quiz Bank
FoundationalWhat is an environment variable, and how does a process get its environment?
An environment variable is a named piece of text, such as PATH or NODE_ENV, that a process carries and that programs read for configuration. A process receives its environment as a copy of its parent's environment at the moment it is started; after that, changes in the parent do not reach the child and changes in the child do not reach the parent. So configuration flows down a tree of processes, from the system's settings to the desktop or login shell, to terminals, to the programs they start.
FoundationalWhat is the difference between system and user environment variables on Windows?
System environment variables apply to every user and every process on the machine and need administrator rights to change. User environment variables apply only to one user's account. When Windows builds a new process's environment, it combines both: for most names the user's value wins, but PATH is joined, system entries first then user entries. Both are stored in the registry, system ones under HKLM and user ones under HKCU\Environment. Changes appear only in processes started afterwards.
AppliedWhy does running a script that does `export DEBUG=1` not change the shell you ran it from, and how do you make it do so?
The shell runs the script as a child process, which gets a copy of the shell's environment. export changes only that child's copy, and the copy disappears when the script exits, so the parent shell is unchanged. To change the current shell, run the script's commands inside the shell itself with source script.sh, or . script.sh, instead of as a separate process.
InterviewWhat is the Windows Registry, and how does it contrast with Unix configuration?
The Registry is Windows's single, hierarchical, typed database of system and application settings: keys that contain keys and typed values, under root keys such as HKEY_LOCAL_MACHINE for the machine and HKEY_CURRENT_USER for the logged-in user, stored on disk in hive files. Unix instead keeps configuration in plain text files scattered across /etc and users' home folders. The registry gives one consistent, fast, typed store with built-in machine and user scopes, but it is opaque, awkward to version-control and a shared point of failure. Text files are transparent, easy to search and keep in Git, and independent, but inconsistent in format and location. It is a central-versus-distributed trade-off.
InterviewWhy do platforms configure applications through environment variables, and what is the main risk?
Environment variables let the same built program, or container image, run in different environments without any change to its code or files: only its environment differs between development, testing and production, and every language can read them. That makes deployments reproducible and configuration easy to change.
The main risk is secrets. Environment variables are inherited by every child process, may be printed by tools that dump their environment when they fail, and on Linux can be read through /proc/<pid>/environ by the same user. Sensitive values are safer in files with tight permissions, mounted by the platform, or fetched from a secrets manager at startup.
StaffA Windows build agent sometimes picks up an old version of Node even though the new version is installed. Using this page, list the likely causes and how to make builds deterministic.
Likely causes, all about how PATH is built and inherited:
- Stale environment: the agent service started before the installation and still holds its old copy of
PATH; only a restart of the agent gives it the new one. - Order of entries: both versions' folders are in
PATH, and the old one comes first, either in the system part, which always precedes the user part, or earlier within one part. - Different scopes: the new version was installed for one user, but the agent runs as a different account, so it never sees that user's
PATH. - A wrapper or version manager that sets its own
PATHfor some shells but not for the agent.
To make builds deterministic, do not depend on whatever is on PATH: pin the Node version in the build definition and install or select it explicitly at the start of each job, print node --version in the log, and ideally run builds in a container image that contains exactly the required tools.
Scenario Drill
DrillA teammate adds the photo-upload service's tools folder to their user PATH, and the tools work in their terminal, but a scheduled task running the nightly build cannot find them. Using this page, explain why and fix it.
The tools were added to the teammate's user PATH, which only applies to their own account. The scheduled task almost certainly runs as a different account, such as a dedicated build user or the system account, which never receives that user's variables. Even if it did run as the same user, it would only see the change if the task process started after the change was made.
Fix it by choosing the right scope. If every account on the machine should have the tools, add the folder to the system PATH, which needs administrator rights, and restart the scheduler or the task. Better, make the nightly build independent of PATH entirely: call the tools by their full path, or set PATH explicitly at the start of the build script, so the build behaves the same whoever runs it and whenever.
Next: the registry and environment variables hold settings for one machine. Companies need settings, files and identities that span thousands of machines. Page 2.9.4 explains the three pieces of the enterprise Windows stack: NTFS permissions, SMB file sharing and Active Directory.