Environment Variables from Zero: export, .env Files, and Secrets That Reach Only One Command
API keys, database addresses, port numbers — they must not live in code, they live in environment variables. This guide starts from zero: shell var vs exported var, one-shot values for a single command, .env files with set -a, defaults and required checks, unset and env -i. Every step was run for real on GNU bash 5.2.21; the transcript is included.

Sooner or later every vibe project hits the same problem: the code is written, but to run it needs a string of secrets — which model's API key, which database address, which port the service runs on. None of that can live in the code: put it there and push to GitHub, and you have published it; leave it out and the program will not run. Their home is the environment variable. This guide starts from zero: what an environment variable is, how a shell variable and an environment variable differ by exactly one export, how to pass a value to just one command, how a .env file works, and the pitfalls beginners hit most. Every step was run for real on GNU bash 5.2.21, with the output in the test record at the end; every line of output quoted here matches that record word for word.
First, what an environment variable is. When a program starts, the operating system hands it a list of name-value pairs, in the form name=value — HOME=/home/lee, PATH=/usr/bin:/bin, and so on. The Bash manual puts it plainly: "When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the form name=value." That list is passed unchanged to the program's child processes, and then to their children, generation after generation. Every command you type in your shell is a child process of the shell, so all of them can read the list. Read the other way round, an environment variable is a note a parent process leaves for its children — whatever is written on the note, every generation below can see it.
The environment variables you meet most often are ones you already use without noticing. PATH tells the shell which directories to search for commands — the reason typing python3 finds it is that its directory is in PATH. HOME tells programs where your home directory is; many tools keep their configuration under HOME. LANG decides which language programs speak to you in. The most direct way to look at the list is printenv: with no argument it prints everything, with a name it prints just that one. In our test run, printenv DEMO277_MODE printed nothing at all when the variable did not exist, and exited with code 1 — "there is no such variable" is itself an answer, and a script can use the exit code to test whether a variable exists.
1. Shell variables vs environment variables: exactly one export apart
The two ideas beginners confuse most are shell variables and environment variables. They look identical — both are name=value — and the difference is exactly one thing: export. Without export it is a shell variable, alive only in the current shell; once exported it is an environment variable, passed on to child processes. The test run shows it clearly: first set MYAPP_NAME=demo277-env, then ask a child bash to print it, and the output is child sees shell var: [] — empty brackets, the child saw nothing. Then export MYAPP_NAME and ask again, and the output becomes child sees exported var: [demo277-env]. The same assignment, the same name, only one export apart — and the child's experience is completely different.
That difference explains a lot of "I set it, so why can't it be read" confusion. Write A=1 in a terminal, then run a program that reads A, and it reads nothing — because A is only a shell variable. The other way round: a variable exported inside a script file dies when the script's shell exits, because export only passes downwards. A child process that changes its own environment variables never changes its parent's. Remember the direction: environment variables flow one way, downwards — parent to child, child to grandchild, never back up.
By the way, export is not the only spelling. declare -x marks a variable for passing to child processes too, with the same effect as export — it is just used less often in everyday work. Knowing it exists is enough, so that declare -x in someone else's script does not stop you.
2. Passing a value to just one command: assignment before the command
Sometimes you want just one command to see a variable, without dirtying the whole shell. The way is to put the assignment in front of the command: DEMO277_MODE=once bash -c 'echo "one-shot child: [$DEMO277_MODE]"'. In the test run the output is one-shot child: [once] — the command's child saw it. Run the same command again immediately afterwards without the assignment and the output is one-shot after: [] — the variable is already gone, it lived only as long as that one command. The Bash manual's own words: "If any parameter assignment statements appear before a simple command, the variable assignments are part of that command's environment for as long as it executes."
The env command does the same thing, spelled env DEMO277_MODE=once bash -c '...' — either spelling works, just pick one and keep it consistent across a team. The advantage of giving a value to one command only is cleanliness: try a switch once without exporting first and unsetting afterwards, and without worrying that the variable lingers in the shell and gets misread by a different command later. Temporarily swapping an API key for one call, or turning log verbosity up to maximum for one run, are everyday uses of this spelling.
3. The .env file: write the config in a file, load it when you need it
Once a project has more than a couple of settings, exporting them one by one stops making sense. The common practice is a .env file, one name=value per line. The one in our test run has just three lines: DEMO277_APP_NAME=demo277-env, DEMO277_APP_PORT=3000, and DEMO277_API_KEY=demo277-not-a-real-key. Note the third line: it is a fake key, a placeholder. A real key should never appear in an example, a screenshot, or a chat log — section 7 explains why.
The way to load a .env file is source .env, which makes the current shell execute the assignments in it. But this is where the first real pitfall of this guide hides. source only executes the assignments; the variables it creates are shell variables by default, and are not automatically exported. In the test run we wrote a tiny script, check-env.sh, whose only job is to print DEMO277_APP_PORT, then sourced .env in a child shell and ran it: the output is grandchild sees: [] — the grandchild saw nothing. Change it to set -a before sourcing, and the output becomes grandchild sees: [3000]. set -a means "from now on, every assignment is automatically exported"; turn it off again afterwards with set +a. That little switch is the line between a .env file that works and one that does not: many tutorials write source .env and never mention set -a, and everyone who follows them hits the same strange "I sourced it, but the program still cannot read it" problem.
After loading, verify it by hand: printenv DEMO277_APP_NAME prints demo277-env, printenv DEMO277_APP_PORT prints 3000, and printenv DEMO277_API_KEY prints demo277-not-a-real-key. All three values are there, so the three lines really did enter the environment. One more detail: a .env file is not a standard, and Bash has no built-in .env loader — source simply runs it as a shell script. So lines starting with export, comments, and blank lines all work, but assignments with spaces or nested quotes can surprise you, because every line is ultimately shell syntax.
4. Spaces around the equals sign: one space is enough to lose the command
Shell assignments cannot have spaces around the equals sign, a rule that feels wrong the first time you meet it: A = 1 is perfectly normal in most languages, but in a shell it is an error. In the test run, bash -c 'DEMO277_BAD = 1' prints bash: line 1: DEMO277_BAD: command not found and exits with code 127. The shell treats DEMO277_BAD as the name of a command to find, cannot find it, and complains. Remember: an assignment is name=value written in one breath, with not a single space in the middle. The error message is at least honest — "command not found" is the shell telling you it took your variable name for a command.
5. Defaults and required values: what happens when the variable is missing
When a program reads environment variables, the two situations to fear are a missing variable crashing the program, and a missing variable silently taking a wrong value. The shell offers two spellings. The first is a default: ${DEMO277_NOPE:-8080} means "use DEMO277_NOPE if it has a value, otherwise use 8080". In the test run the output is default port: 8080 with exit code 0 — the variable does not exist, the program runs anyway, on the default. That spelling fits settings with a sensible default, like ports and timeouts.
The second is a required value: ${DEMO277_NOPE:?missing!} means "this variable must exist, otherwise fail and stop". In the test run the output is bash: line 1: DEMO277_NOPE: missing! with exit code 127. The program never starts; the shell stops you first. That spelling fits settings where running without a value would be wrong anyway, like keys and database addresses: failing early is far cheaper than failing halfway through. A few required-value checks at the top of a startup script is a habit many projects share.
6. Removing and emptying: unset and env -i
When you are done with a variable, remove it: unset DEMO277_TOKEN, and printing it afterwards gives after unset: [] — empty. unset removes the variable from the current shell; a child process that already received a copy keeps its own, because a note that has been passed on cannot be taken back — all you can guarantee is that processes started later will not get it.
More thorough is env -i, which starts a command with an empty environment list. In the test run, env -i DEMO277_ONLY=1 printenv prints exactly one line, DEMO277_ONLY=1 — nothing except the one variable you handed it yourself, not even HOME or PATH. That is exactly its use: when debugging, run in a clean environment first and confirm the program depends only on the variables you gave it, not on some variable that happens to be sitting in your shell.
But env -i has a pitfall we caught by hand in the test run: env -i PATH=/tmp/demo277-env/empty-bin bash -c 'command -v python3' prints env: 'bash': No such file or directory and exits with code 127. The problem is that once env -i has cleared PATH, env itself has to find the bash command, and PATH now contains only an empty directory — bash is nowhere to be found. The fix is to write the command as an absolute path: env -i PATH=/tmp/demo277-env/empty-bin /usr/bin/bash -c 'command -v python3 || echo "python3 not found"' prints python3 not found with exit code 0. The lesson is practical: when you empty the environment, the first command must be an absolute path, or the tool that starts commands cannot find its own way.
7. Where secrets live matters: every child process can see them
The greatest strength of environment variables — that they are passed down to every child process — is also their greatest risk. Any program started from your shell can read every variable you exported. In the test run, after export DEMO277_TOKEN=demo277-secret, printenv DEMO277_TOKEN prints demo277-secret straight away, with no resistance at all. That is not a bug, it is the design: environment variables are a channel for passing messages to child processes.
So there are three rules. First, never put a real key in code, in a commit, or in a chat screenshot — the Config chapter of The Twelve-Factor App states it plainly: config must be strictly separated from code, and the test is whether "the codebase could be made open source at any moment, without compromising any credentials". Second, put the .env file in .gitignore and never commit it; commit a .env.example instead, with only variable names and fake values, telling others which variables the project needs. Third, put a key only into the environment of the run that needs it: a .env file for local development, the deployment platform's settings screen or a secrets manager on a server — never an export API_KEY=... line in shell history that gets saved for a long time.
8. PATH is the environment variable you use most: how commands get found
Of all environment variables, the one you deal with most is PATH. It is a list of directories separated by colons, and when the shell looks for a command it searches those directories in order. Type python3, and the shell looks in the first directory in PATH for an executable called python3, then the second, until it finds one or runs out of directories. Running out of directories gives you command not found — an error you have certainly seen. It does not mean "this command does not exist", it means "none of the directories in PATH has it".
The order of PATH matters: directories earlier in the list win. If the same command exists in two directories, the shell always uses the one that comes first. So if you want a tool you installed yourself to take priority over the system's copy, put its directory at the front: export PATH="$HOME/bin:$PATH" — your directory first, then the original PATH. If you only want to add a directory temporarily, appending it is safer: export PATH="$PATH:$HOME/bin", and system commands keep their priority. The easiest mistake when editing PATH is losing the original: export PATH="$HOME/bin" replaces all the system directories, and after that even ls cannot be found. Remember: when you change PATH, always carry the original $PATH along in the new value.
One more detail: the current directory is not in PATH. Even standing right next to an executable file, typing its name will not find it — you have to write it with a path, like ./run.sh. That is a deliberate safety design: it stops someone leaving a malicious script with a system command's name in a directory you happen to walk through. To run a script you wrote yourself, first chmod +x, then run it as ./name, or put it in a directory that is already in PATH.
9. Three habits for reading variables in scripts
When writing scripts, there are three common habits for reading environment variables. The first is reading directly: PORT=${PORT:-3000} — use 3000 when nothing is set — which fits settings with a sensible default. The second is a required check: : "${API_KEY:?API_KEY is required}", placed at the top of the script, which fails and exits immediately when API_KEY is not set, without even running the colon command — the colon is an empty command here, and the whole line exists only to trigger the question-mark check. The third is testing first and then deciding: if [ -z "$DATABASE_URL" ]; then echo "DATABASE_URL is not set"; exit 1; fi, where -z means "the string is empty" — which fits when the error message needs to say more, for example where to find the value.
None of the three is better than the others; they fit different occasions: defaults for ports and timeouts, required checks for keys and addresses, if tests for friendly errors that a human will read. What they share is this: do not wait until the program is halfway through before discovering a variable was never set. Three lines of checks at startup are far cheaper than an hour of reading logs after a deploy. And one point that is easy to overlook: quote variable references in scripts — write "$API_KEY", not $API_KEY. Without quotes, a value containing a space gets split by the shell into several words, and the command after it receives something different from what you meant to give it.
10. The five most common environment variables — learn these and you have enough
There are hundreds of environment variables, but everyday work comes down to five. HOME is your home directory, where programs look for configuration first — many tools keep their settings in hidden directories under HOME. PATH, covered in the last section, is the list of directories the shell searches for commands. LANG decides which language programs speak to you in, and how dates and numbers are formatted; its value usually looks like en_US.UTF-8 or zh_CN.UTF-8, where the UTF-8 at the end is the character encoding, and most garbled-text problems trace back to it. SHELL is the path of the shell you are using, such as /bin/bash, which programs use when they need to open another shell. USER is your login name, for scripts that need to know who is running them.
Learn these five and other people's scripts and error messages become much easier to read. A script that starts with HOME="$HOME/.cache/myapp" is writing a cache under your home directory; an error message mentioning LANG is a hint to check language and encoding settings. One small habit helps too: to see a variable's current value, printenv with its name is enough; to see everything, env or printenv with no argument. Do not make do with echo $PATH — when a value contains spaces, echo eats the formatting, while printenv prints it exactly as it is, which is more reliable.
11. Checklist: follow this next time you set up an environment
Setting up a new project's environment, walk through this in order. First, list the variables it reads, write them into .env.example, and use placeholders for every value. Second, copy that file to .env, fill in the real values, and confirm .env is in .gitignore. Third, load it with set -a; source .env; set +a, then check each variable by hand with printenv. Fourth, before starting the program, ask whether any variable is required — and if so, add a ${VAR:?} check. Fifth, once it runs, write down the variable names you used — next time the same project moves to another machine or another person takes over, that list sets it up in ten minutes.
Test record: every step above was run for real on GNU bash 5.2.21, and the full output is in demo277_env.sh and demo277_env_transcript.txt (63 lines). Environment variables are not hard; the hard part is building the habits: keep config separate from code, let secrets live only in the environment and never in the repository, and verify every load by hand. Do those three things, and configuration will stop biting you when you change projects, change machines, or hand over to a teammate.
Comments (0)
Sources
Related articles
cron is the scheduling daemon that has run on Linux for decades: write a crontab file saying 'run this command at this time', and it handles the rest. This guide runs everything for real on Debian cron 3.0pl1-162 — installing a job, waiting one minute for the trigger, verifying the log, removing the job — plus special strings, five classic mistakes, and a real 3 a.m. log-archiving job.
ping does exactly one thing: send an ICMP echo request, wait for the echo reply, and report the round-trip time and packet loss. This guide runs every command for real on iputils ping 20240117 — packet count, interval, quiet mode, packet size, timestamps, IPv4 vs IPv6, the three failure modes, exit codes 0/1/2 — with output pasted verbatim.
cut does one thing: split each line into fields on a delimiter and output the fields you ask for. This guide runs every command for real on GNU coreutils 9.4 — field lists and ranges, CSV and output delimiters, character slicing, --complement, the -s rule for lines without a delimiter, log-column statistics, and the quoted-comma limit — with the output pasted verbatim.