Computing Foundations › The Command Line › Day 11

Day 11: Environment Variables and Shell Configuration

Day 11 of 365 — 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.

Course
Computing Foundations
Category
The Command Line
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

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

  1. 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
  2. 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
  3. 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.
  4. 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:

Prerequisites

Why this matters


The idea in plain language

Diagram: how exporting a variable makes it visible to child processes


Historical background


What it is — and what it is not

Diagram: environment inheritance flowing downward only

It is:

It is not:


Why it was created and what problems it solves

Diagram: the layers a configuration value can come from


How it works

PATH and how a command is found

Flowchart: the shell searches each PATH directory in order until it finds the command

The variables you will meet everywhere

Diagram: shell variables compared with exported environment variables

VariableWhat it holdsWhy it matters
PATHDirectories searched for commandsDecides which program, and which version, runs
HOMEYour home directory~ expands to it; tools store settings under it
USERYour login nameScripts and prompts use it
SHELLYour login shellNot necessarily the shell running right now
LANGLanguage and encodingGoverns messages, sorting, and byte decoding
EDITORWhich editor tools should openGit launches it for commit messages
PWDCurrent working directoryUpdated as you cd

Configuration files: login versus interactive

Diagram: which shell configuration files load for login versus interactive shells

ShellLogin shell readsInteractive shell reads
bash/etc/profile, then the first of ~/.bash_profile, ~/.bash_login, ~/.profile~/.bashrc
zsh~/.zshenv, then ~/.zprofile, then ~/.zshrc~/.zshenv, then ~/.zshrc

Aliases and functions

alias ll='ls -la'
alias gs='git status'

mkcd() {
  mkdir -p "$1" && cd "$1"
}

An everyday analogy

Diagram: the login shell compared with the currently running shell

A new employee’s welcome pack.

The workplaceThe environment
The pack handed over on day oneThe environment at process start
Your desk locationHOME
Your name badgeUSER
The list of floors you may searchPATH
The language the handbook is inLANG
A photocopy, not the originalInheritance by copy

Examples in practice

Diagram: how PATH order decides which version of a command runs


Implications: security, privacy, performance, scalability, and cost


Alternatives: free, open source, and commercial

Diagram: safe and unsafe places to keep an API key

ApproachTypeWhen it fits
Plain export in your configFree, built inPersonal settings on your own machine
.env plus direnvFree, open sourcePer-project variables, loaded on cd
python-dotenvFree, open sourceLoading .env from inside a Python program
pass, gopassFree, open sourcePersonal secrets, encrypted at rest
1Password / Vault / cloud secret managersCommercial or free tierTeams, rotation, audit trails
Platform environment settingsIncludedProduction, where the platform injects them

TermWhat it actually is
Shell variablePrivate to the current shell
Environment variableExported, and inherited by children
AliasA name that expands to text before execution
FunctionA small program defined inside the shell
BuiltinA command the shell implements itself, with no file
Config fileA script the shell runs at startup

When to use it — and when not to

Diagram: shell aliases compared with shell functions


The AI connection

Diagram: how activating a virtual environment changes PATH

Diagram: why an edited shell config file appears to have no effect


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 doingCommand
Set a shell variablegreeting="hello"
Show a child cannot see itbash -c 'echo "$greeting"'
Export it and retryexport greeting then repeat
See only exported onesprintenv | head
Find what actually runscommand -v python3 and type python3
Add a directory to PATHexport PATH="$HOME/bin:$PATH"
Make it permanentAdd that line to ~/.zshrc, then source ~/.zshrc

Expected output


hello
/usr/bin/python3
python3 is /usr/bin/python3

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What is the difference between a shell variable and an environment variable?

  1. A shell variable holds numbers while an environment variable holds text
  2. A shell variable is permanent while an environment variable disappears at power-off
  3. A shell variable is private; an exported one is inherited by children
  4. 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?

  1. The one in /bin, because it is the most trusted system directory
  2. Both run, one after the other
  3. Neither; a name in two directories causes an error
  4. 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?

  1. It marks a variable to be inherited by child processes
  2. It saves the variable permanently to a file on disk
  3. It creates a new variable that did not exist before
  4. 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?

  1. nano is not installed, so the setting is ignored
  2. Your shell is zsh, which reads ~/.zshrc, not ~/.bash_profile
  3. export cannot be used with EDITOR
  4. 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?

  1. Scripts are not allowed to use the export keyword
  2. The terminal locks its environment while a script runs
  3. The script runs as a child, so its changes vanish when it exits
  4. 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?

  1. echo
  2. export
  3. printenv
  4. 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)?

  1. ~/.bashrc
  2. ~/.bash_profile
  3. /etc/passwd
  4. ~/.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?

  1. Paste the key directly into your source code and commit it
  2. Put the key in an environment variable, via a gitignored .env file
  3. Email the key to yourself so you always have a copy
  4. 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


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.