Quiz
Warm-up from lesson 6-2: in that kill example you wrote pid=$! and later used $pid. What was that?
Shell variables
Variables are how real software gets configured: API keys, database addresses, and "which mode to run in" are all handed to programs through the environment rather than typed into code. And PATH, at the end of this lesson, explains the single most common broken-machine symptom — command not found for a tool you just installed.
A variable stores a value under a name:
city="Lisbon" echo "Next stop: $city"
Three rules that bite beginners:
- No spaces around =.
city = "Lisbon"fails, because the shell thinkscityis a command. - Read a variable with
$name. Without the dollar sign you get the literal word. - Use double quotes around text containing
$name. Inside double quotes the variable expands, inside single quotes it stays literal.
Variables you didn't set also exist: the environment variables the OS provides, like $HOME (your home directory) and $USER (your username). See them all with the env command.
Code exercise · bash
Run it. One variable, used twice. Then change Lisbon to another city and run again to feel the point of variables: one edit updates every use.
export: sharing with child processes
A plain variable belongs to your shell only. Programs your shell starts (child processes, lesson 6-2) don't see it unless you export it:
snack="olives" # private to this shell export snack # now children inherit it
That's the actual difference between a "shell variable" and an "environment variable": exported ones travel to children. The demo below proves it with bash -c '...', which starts a brand-new child shell to run one command.
Code exercise · bash
Run it. Before export, the child shell sees nothing between the brackets. After export, it sees the value.
PATH: how the shell finds commands
When you type ls, how does the shell know where the ls program lives? It reads the environment variable PATH, a colon-separated list of directories:
/usr/local/bin:/usr/bin:/bin
It checks each directory in order and runs the first ls it finds (which ls shows you the winner).
This explains a rite of passage: your own script won't run by name because your current directory is not on PATH. That's why you type ./myscript.sh, the explicit relative path from lesson 2-1. In unit 8 you'll do exactly that.
Quiz
You wrote a script called deploy.sh, you're standing in its directory, but typing `deploy.sh` gives "command not found". Why?
Code exercise · bash
Your turn. Create two variables, `name` with the value Ada and `language` with the value bash, and print exactly: ``` Ada is learning bash ```