Computing Foundations › The Command Line › Day 11
Day 11: Environment Variables and Shell Configuration
After this lesson you will be able to read and set environment variables, explain how PATH decides which command runs, edit the correct shell configuration file for your shell, and keep secrets like API keys out of version control.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-011-environment-variables-and-shell-configuration
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/computing-foundations/day-011-environment-variables-and-shell-configuration - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Distinguish a shell variable from an environment variable and explain what export does
- Explain how the shell uses PATH to resolve a bare command name, and diagnose "command not found" and wrong-version problems
- Name and describe the most important environment variables — PATH, HOME, USER, SHELL, LANG, EDITOR — and what each controls
- Identify which configuration file a shell reads for login versus interactive sessions in bash and zsh, and edit the correct one
- Define aliases and functions and place them in a config file so they persist across new terminals
- Store secrets such as API keys in environment variables and dotenv files kept out of version control, and describe how direnv automates this
Prerequisites
- Days 8-10: comfort opening a terminal, navigating the filesystem, and running basic commands
- A computer running macOS or Linux (Windows via WSL) with a bash or zsh shell
Why this matters
-
Every API key you will ever use lives in an environment variable. That is the standard, and today is where you learn why.
-
PATHdecides which Python runs, and running the wrong one is the single most common cause of “the library is installed but the import fails”. -
Configuration-as-environment is how the same code runs on your laptop, in CI and in production without changing a line.
-
Your shell config is where your speed comes from. Aliases and functions you write once follow you to every machine.
-
The most common shell bug in existence is editing the file your shell does not read. You will meet it today, deliberately.
The idea in plain language
-
The environment is a set of name-value pairs every process receives when it starts.
-
A shell variable is private to your shell. Programs it launches cannot see it.
-
An exported variable is in the environment, and every child process inherits a copy.
-
exportis the whole difference.setlists all shell variables;envlists only the exported ones. -
Assignment takes no spaces:
greeting="hello", nevergreeting = "hello".
Historical background
-
The environment arrived with Unix in the 1970s, as a way to pass settings to a program without inventing a command-line flag for each one.
-
The design decision that stuck: pass a copy at process creation, so a program can never reach back and alter its parent.
-
PATHsolved a specific problem — letting users typelsrather than/bin/ls, while still letting a site put its own tools first. -
Startup files followed, so a user’s settings survived logging out.
-
The convention became universal. Twelve-factor app methodology, Docker, Kubernetes and every CI system configure through the environment, for the reason the original designers chose it: it is the one interface every program already understands.
What it is — and what it is not
It is:
- A list of strings handed to each process at creation.
- The standard place for configuration that varies by machine.
- Inherited downward, once, as a copy.
It is not:
-
Not shared memory. Changing a variable after a child starts does not reach it.
-
Not a way for a script to change your shell. A script runs in a child, and children cannot alter their parent — which is why config files are sourced, not executed.
-
Not encrypted. An environment variable is plain text to anything that can read the process.
-
Not a database. It is small, flat, and read once.
Why it was created and what problems it solves
-
Configuration without recompiling. The same binary behaves differently by environment alone.
-
Machine-specific paths. Your home directory is not mine, and no program should need to know either.
-
Secrets outside source code. A key in the environment is a key that is not in your repository.
-
Consistency across environments. Development, staging and production run the same code with different variables.
-
A universal interface. Every language can read the environment, so it is the one configuration channel that needs no library.
How it works
PATH and how a command is found
-
PATHis one string of directories separated by colons, like/usr/local/bin:/usr/bin:/bin. -
A command with no slash triggers the search. The shell walks the list left to right and runs the first executable of that name it finds.
-
It never looks anywhere else, and it stops at the first match.
-
command -v python3prints the full path it would actually run. -
type python3says whether the name is a program, a builtin, an alias or a function — and where it resolves.
The variables you will meet everywhere
| Variable | What it holds | Why it matters |
|---|---|---|
PATH | Directories searched for commands | Decides which program, and which version, runs |
HOME | Your home directory | ~ expands to it; tools store settings under it |
USER | Your login name | Scripts and prompts use it |
SHELL | Your login shell | Not necessarily the shell running right now |
LANG | Language and encoding | Governs messages, sorting, and byte decoding |
EDITOR | Which editor tools should open | Git launches it for commit messages |
PWD | Current working directory | Updated as you cd |
-
SHELLnames your configured login shell, not the process reading your keystrokes. Typebashinside zsh andSHELLmay still say/bin/zsh. -
LANGis not cosmetic. It governs how bytes become characters — Day 5’s encoding ideas, surfacing as one variable.
Configuration files: login versus interactive
-
A shell is a login shell if it is the first of a session — what SSH drops you into, or a new macOS Terminal tab.
-
A shell is interactive if it is reading commands you type rather than running a script.
-
A shell can be both, one, or neither, and each combination reads different files.
| Shell | Login shell reads | Interactive shell reads |
|---|---|---|
| bash | /etc/profile, then the first of ~/.bash_profile, ~/.bash_login, ~/.profile | ~/.bashrc |
| zsh | ~/.zshenv, then ~/.zprofile, then ~/.zshrc | ~/.zshenv, then ~/.zshrc |
-
The bash convention exists because those paths diverge: put your real settings in
~/.bashrcand addsource ~/.bashrcto~/.bash_profile, so both kinds of shell end up identical. -
On macOS, edit
~/.zshrc. A new Terminal tab is an interactive login shell running zsh. -
Put a setting in the file the shell actually reads, or it silently does nothing.
Aliases and functions
alias ll='ls -la'
alias gs='git status'
mkcd() {
mkdir -p "$1" && cd "$1"
}
-
An alias is text substitution. Typing
llrunsls -la. -
A function takes positional arguments.
mkcd projectmakes the directory and moves into it, using$1. -
Both belong in your config file, where they load in every new shell.
An everyday analogy
A new employee’s welcome pack.
| The workplace | The environment |
|---|---|
| The pack handed over on day one | The environment at process start |
| Your desk location | HOME |
| Your name badge | USER |
| The list of floors you may search | PATH |
| The language the handbook is in | LANG |
| A photocopy, not the original | Inheritance by copy |
- Everyone gets a copy, so scribbling on yours changes nothing for anyone else.
- New hires get whatever the pack said on their first day, not what it says now.
- You cannot edit your manager’s copy by editing your own — which is exactly why a script cannot change your shell.
Examples in practice
-
pip installsucceeds andimportfails:pipandpython3resolve to different installations.command -vboth, and compare. -
A tool works in one terminal and not another: one is a login shell, the other is not, and only one read the file you edited.
-
OPENAI_API_KEYin.env, loaded at start: the standard pattern, and safe only if.envis in.gitignore. -
A cron job that cannot find a command: cron runs with a minimal environment and a short
PATH. Use absolute paths there. -
A container that behaves differently from your laptop: usually one variable, usually
PATHorLANG.
Implications: security, privacy, performance, scalability, and cost
-
Security: the environment is the right home for secrets, and still a surface. A key there is not in your code — but it is readable by the process and every child, and captured by anything that logs the environment for debugging.
-
Prefer the environment to the command line. Arguments are visible in
psto every user on the machine. -
Privacy:
printenvreveals your username, home path, locale and toolchain. Redact before pasting it into a bug report. -
Performance: a long
PATHslows every lookup, and a network-mounted directory onPATHslows it badly. Shells cache resolved locations, which is why a freshly installed tool sometimes needshash -ror a new shell. -
Scalability: this is why deployment platforms configure through variables. It reaches from one laptop to thousands of servers without touching code.
-
Cost: a committed key can become a stolen key and a real bill. The few minutes spent here pay for themselves the first time.
Alternatives: free, open source, and commercial
| Approach | Type | When it fits |
|---|---|---|
Plain export in your config | Free, built in | Personal settings on your own machine |
.env plus direnv | Free, open source | Per-project variables, loaded on cd |
python-dotenv | Free, open source | Loading .env from inside a Python program |
pass, gopass | Free, open source | Personal secrets, encrypted at rest |
| 1Password / Vault / cloud secret managers | Commercial or free tier | Teams, rotation, audit trails |
| Platform environment settings | Included | Production, where the platform injects them |
direnvis the biggest single upgrade here. It loads and unloads variables as you enter and leave a directory, which stops per-project settings leaking into every other project.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Shell variable | Private to the current shell |
| Environment variable | Exported, and inherited by children |
| Alias | A name that expands to text before execution |
| Function | A small program defined inside the shell |
| Builtin | A command the shell implements itself, with no file |
| Config file | A script the shell runs at startup |
When to use it — and when not to
-
Use environment variables for anything that differs between machines — paths, hostnames, credentials, feature switches.
-
Use them for every secret. Never in source, never in a committed file.
-
Use a function rather than an alias the moment you need an argument anywhere but the end.
-
Do not use the environment for structured data. It holds flat strings; JSON in a variable is a sign you need a config file.
-
Do not use it for anything large. The environment is copied into every child process, and there are size limits.
-
Do not scatter exports across five files. One place, sourced, or you will spend an afternoon finding which one wins.
The AI connection
-
Every model provider reads a key from the environment.
OPENAI_API_KEY,ANTHROPIC_API_KEY,HF_TOKEN— the same pattern each time. -
CUDA_VISIBLE_DEVICESdecides which GPUs your job can see, and is how you share a multi-GPU machine without arguing. -
HF_HOMEandTRANSFORMERS_CACHEdecide where tens of gigabytes of downloaded weights land. Set them before you fill your home partition, not after. -
Virtual environments work by editing
PATH. Activating one prepends itsbindirectory, so itspythonwins the search. That is the entire mechanism. -
Reproducibility is an environment problem far more often than a code problem.
Knowledge check
quiz:
question: "A script ends with a line that changes directory and exports a variable, but after running it your shell is unchanged in both respects. Why?"
options:
- "The script ran in a child process, and a child cannot alter its parent's state"
- "The script lacked execute permission, so its final lines never ran"
- "Exported variables require a new login session before they take effect"
- "The script's changes were applied but the shell caches the old values"
answer_index: 0
explanation: "Running a script creates a child process that inherits a copy of the environment. Nothing it does travels back up. Sourcing the file instead runs it in the current shell, which is why config files are sourced."
Hands-on exercise
Prove inheritance, then fix a PATH problem you created. Worked through fully in
the Day 11 lab directory.
| What you are doing | Command |
|---|---|
| Set a shell variable | greeting="hello" |
| Show a child cannot see it | bash -c 'echo "$greeting"' |
| Export it and retry | export greeting then repeat |
| See only exported ones | printenv | head |
| Find what actually runs | command -v python3 and type python3 |
| Add a directory to PATH | export PATH="$HOME/bin:$PATH" |
| Make it permanent | Add that line to ~/.zshrc, then source ~/.zshrc |
Expected output
hello
/usr/bin/python3
python3 is /usr/bin/python3
- The first line is empty — the child never received the unexported variable.
- The second prints
helloafterexport. - Prepending to
PATHputs your directory first, so your version wins.
Validate your work
- You demonstrated the difference between a shell and an environment variable
- You can state which config file your shell reads, and why
- You added a directory to
PATHand ran a command from it by bare name - You wrote one alias and one function, and both survive a new terminal
- You sourced a config file rather than opening a new window
-
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
Your edit did nothing. Wrong file, or an open shell that has not re-read it. Check
echo $0, thensourcethe right file. -
greeting = "hello"fails. No spaces around the equals sign; the shell reads it as a command namedgreeting. -
PATHbroken and most commands gone. Open a new terminal. The damage was only in that shell. -
A newly installed command is not found.
hash -r, or open a new shell.
Common mistakes
-
Appending to
PATHwhen you meant to prepend, so the old version keeps winning. -
Committing
.env. Add it to.gitignorebefore the first commit, not after — git does not forget. -
Overwriting
PATHinstead of extending it. Always include$PATHin the new value. -
Editing
~/.bash_profileon a zsh machine.
Practice assignment
-
Write five aliases and two functions you would genuinely use, and put them in your config file. Live with them for a day and delete the ones you did not touch.
-
Break
PATHdeliberately in a throwaway shell and recover without closing the window. -
Create a
.envand a.env.example, add the first to.gitignore, and confirm withgit statusthat only the example is tracked. -
Find which config files your shell reads by adding an
echoto each and opening a new terminal.
Extension challenge
-
Install
direnvand set up a project directory whose variables load on entry and unload on exit. Explain why this is safer than global exports. -
Trace a virtual environment’s mechanism. Print
PATHbefore and after activating one, and identify exactly what changed. -
Write a function that switches between two API keys and prints which is active, without ever printing the key itself.
-
Find the environment size limit on your system and explain why a very large variable can make a program fail to start at all.
Quiz
Q1. What is the difference between a shell variable and an environment variable?
- A shell variable holds numbers while an environment variable holds text
- A shell variable is permanent while an environment variable disappears at power-off
- A shell variable is private; an exported one is inherited by children
- There is no difference; the two terms are interchangeable
Show answer
Answer: C. A shell variable is private; an exported one is inherited by children
Every variable starts private to the shell. Only when you export it does it join the environment, the set of values the operating system copies to every child process the shell launches.
Q2. You type the command `format` and your PATH is `/usr/local/bin:/usr/bin:/bin`. An executable named `format` exists in both `/usr/bin` and `/bin`. Which one runs?
- The one in /bin, because it is the most trusted system directory
- Both run, one after the other
- Neither; a name in two directories causes an error
- The one in /usr/bin, because it comes first on PATH
Show answer
Answer: D. The one in /usr/bin, because it comes first on PATH
The shell searches PATH left to right and runs the first match. Since /usr/bin appears before /bin, its copy wins. This ordering is why the wrong version of a tool sometimes runs.
Q3. What does the `export` keyword actually do?
- It marks a variable to be inherited by child processes
- It saves the variable permanently to a file on disk
- It creates a new variable that did not exist before
- It deletes the variable from the current shell
Show answer
Answer: A. It marks a variable to be inherited by child processes
export does not create or persist a variable; it marks the name so that its value is copied into the environment of every command the shell runs from then on. The variable may already exist beforehand.
Q4. On a macOS machine using zsh, you add `export EDITOR=nano` to `~/.bash_profile`, but new Terminal tabs never pick it up. What is the most likely reason?
- nano is not installed, so the setting is ignored
- Your shell is zsh, which reads ~/.zshrc, not ~/.bash_profile
- export cannot be used with EDITOR
- You must restart the computer for any config change to take effect
Show answer
Answer: B. Your shell is zsh, which reads ~/.zshrc, not ~/.bash_profile
Each shell reads its own configuration files. zsh reads ~/.zshrc (and ~/.zprofile, ~/.zshenv), never ~/.bash_profile. Putting the setting in the file your shell actually reads is the fix.
Q5. Why can a shell script never change the environment of the terminal that launched it?
- Scripts are not allowed to use the export keyword
- The terminal locks its environment while a script runs
- The script runs as a child, so its changes vanish when it exits
- Only the operating system can change environment variables
Show answer
Answer: C. The script runs as a child, so its changes vanish when it exits
A child process receives a copy of the environment. It can modify its own copy, but that copy is discarded when the child exits. The environment flows strictly downward, from parent to child, never back up.
Q6. Which command tells you the full path that the shell would run for a given command name?
- echo
- export
- printenv
- command -v
Show answer
Answer: D. command -v
`command -v python3` prints the resolved path (or nothing if not found). `type` and `which` give similar information; printenv lists environment variables, and echo prints text.
Q7. Which configuration file does bash read for a non-login interactive shell (for example, a second terminal opened on a Linux desktop)?
- ~/.bashrc
- ~/.bash_profile
- /etc/passwd
- ~/.zshrc
Show answer
Answer: A. ~/.bashrc
bash reads ~/.bashrc for interactive non-login shells and ~/.bash_profile for login shells. Because they diverge, the common convention is to have ~/.bash_profile source ~/.bashrc so both behave the same.
Q8. What is the safe, standard way to give your program an API key without risking it in version control?
- Paste the key directly into your source code and commit it
- Put the key in an environment variable, via a gitignored .env file
- Email the key to yourself so you always have a copy
- Store the key in the git commit message
Show answer
Answer: B. Put the key in an environment variable, via a gitignored .env file
Secrets belong in environment variables, kept out of committed files. A common pattern is a .env file loaded at run time and listed in .gitignore, so the key is present in memory but absent from every file you commit.
Glossary
- environment variable
- A named string value held by a running process and copied by the operating system to every child process it starts, used to pass configuration and secrets without editing code.
- shell variable
- A named value known only to the current shell; unlike an environment variable, it is not inherited by the programs the shell launches unless it is exported.
- export
- A shell keyword that marks a variable to be included in the environment, so that child processes started afterward inherit a copy of its value.
- PATH
- An environment variable holding a colon-separated list of directories the shell searches, in order, to find the executable for a bare command name, running the first match.
- HOME
- An environment variable holding the absolute path to your home directory; the shell expands the shorthand ~ to its value.
- alias
- A short name defined in the shell that expands to a longer command by simple text substitution, such as ll for ls -la.
- shell function
- A named block of shell commands that can take arguments and contain logic, used like a command; more powerful than an alias for anything beyond fixed text substitution.
- .bashrc
- The configuration file bash reads for interactive non-login shells; a common place to define aliases, functions, and exported variables.
- .zshrc
- The configuration file zsh reads for interactive shells; on macOS, where a new Terminal tab runs zsh, this is usually the file to edit for personal settings.
- login shell
- The first shell of a session, such as the one an SSH connection or a new macOS Terminal tab starts; it reads profile files like ~/.bash_profile or ~/.zprofile.
- interactive shell
- A shell that is reading commands a person types, as opposed to running a script non-interactively; it reads files like ~/.bashrc or ~/.zshrc.
- subshell
- A child shell created by wrapping commands in parentheses; variables it sets and exports affect only itself and vanish when it exits, leaving the parent environment untouched.
- dotenv
- A convention of storing environment variables as NAME=value lines in a file (commonly .env) that is loaded at run time and kept out of version control via .gitignore.
- direnv
- An open-source tool that automatically loads a per-directory set of environment variables when you enter a project directory and unloads them when you leave.
Sources and further reading
- Bash Reference Manual — GNU (accessed 2026-07-12) — Authoritative reference for shell variables, export, and the startup files bash reads.
- The Missing Semester of Your CS Education — The Shell — MIT (accessed 2026-07-12) — A practical introduction to the shell, environment, and PATH.
- Environment variable — Wikipedia (accessed 2026-07-12)
- The Linux Command Line — William Shotts (accessed 2026-07-12) — Free book covering the environment and shell configuration for beginners.
- PATH (variable) — Wikipedia (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.