00.2 The Terminal and Shell
Almost everything an AI engineer does starts in a terminal: installing tools, running tests, calling APIs with curl, reading logs with jq, pushing code with git, starting a server, and reading the error a command just printed. This lesson teaches the terminal and the shell from zero: what the prompt is, how commands are built, how to find your way around the file system, how to process text with pipes, how environment variables and PATH work, permissions and processes, the networking tools you'll use against LLM APIs, and enough shell scripting to automate the boring parts — plus the safety habits that keep you (and your keys) out of trouble.
What you'll learn
- The mental model: terminal emulator, shell and command; the prompt; bash, zsh, fish, PowerShell and cmd; the anatomy of a command; exit codes; standard input, output and error; the working directory
- Navigating the file system: absolute and relative paths,
~,.,..,pwd,ls,cd, hidden files, case sensitivity, quoting, globbing - Working with files:
mkdir,touch,cp,mv,rmdone safely,cat,less,head,tail -f,wc,file,du/df, links, and practising inside a scratch folder - Comparing and packaging at awareness level:
difffor file differences,tarfor archives, plus one-line awareness ofcron, launchd and clipboard tools - The Unix toolbox: pipes, redirection,
tee,xargs, command substitution,grep,find,sort,uniq,cut,tr,sed,awk, andjqfor JSON — all with real output - Environment variables,
export,env,printenv,PATH,which/command -v, dotfiles and startup files — and how Python will later read them - Permissions (
chmod, ownership,sudo), executable scripts and the shebang line - Processes and jobs:
ps,top,killand signals, Ctrl+C/Z/D,&,jobs,fg, ports,lsof,nohupandtmux - Networking tools:
ping,curlin depth,wget,ssh/scp,dig/nslookup - Shell scripting: variables, quoting,
if,for, functions,set -euo pipefail, arguments — and when to switch to Python instead - Terminal productivity: keyboard shortcuts,
man,--help,tldr, and the safety rules that matter - A full cheat sheet mapping every task to its macOS/Linux and PowerShell form
What you don't need
- Any programming experience. If you can type, you can do this lesson.
- A fast computer or a paid tool. Everything here runs on a laptop you already own, for free.
- API keys or accounts. Everything in this lesson works offline, except the networking section, which you read rather than run.
Setup
You need two things, both covered in lesson 00.1:
- A terminal — the app where you type commands. On macOS it's Terminal (or iTerm2 if you installed it); on Windows the path recommends WSL 2 (which gives you a Linux terminal inside Windows) or PowerShell; on Linux it's your distribution's terminal app.
- A text editor — VS Code, or any editor you like.
No API key is needed, and nothing here installs software except one optional tool:
brew install jq # macOS — JSON tool used in Part 4 (recent macOS may already have it)
# Ubuntu/Debian: sudo apt install jq
# WSL: same as Ubuntu/Debian
# Windows: winget install jqlang.jq (then use it from WSL or PowerShell)Check what's already there: jq --version (as of November 2026 the latest release is 1.8.x; macOS ships its own build, and brew installs the upstream one — either is fine). Optional extras mentioned along the way: tldr (cheat-sheet pages, 9.2), htop and tmux (process viewers and session managers).
For practice, make a scratch folder so you can experiment without touching real files:
mktemp -d # prints a path like /tmp/tmp.XXXXXXXX — cd into it and delete it when doneThe bash examples assume a bash- or zsh-family shell (macOS, Linux, WSL). Where Windows PowerShell differs, you'll get the PowerShell version in a table or a fenced powershell block. When a command behaves differently on macOS's BSD tools versus Linux's GNU tools, that's called out — it's one of the most common beginner traps.
What you must be able to do after this lesson#
- Explain terminal, shell and command and read an exit code
- Navigate the file system with absolute and relative paths
- Create, copy, move and delete files safely inside a scratch folder
- Combine commands with pipes and redirection
- Set an environment variable and explain how PATH finds a program
- Make a script executable and stop a runaway process
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Run uv add openai in your project folder." |
Parts 2–3: the working directory decides where the package lands |
"curl the endpoint and pipe it to jq." |
Part 4: pipes, redirection and jq |
| "Your key is in the environment, not in the code." | Part 5: export, env, .env files |
"command not found — is it installed or just not on your PATH?" |
5.3 PATH and finding programs |
"The script won't run: Permission denied." |
6.1–6.3: the execute bit and the shebang |
| "Something's already listening on port 8000." | 6.6 Ports: lsof -i :8000 |
| "Your SSH session dropped and the training job died with it." | 6.7 Long-running tasks: nohup, tmux |
"Read the trace JSONL with jq to find the slow span." |
4.8 jq: real JSON querying, used again in 11A.1 |
| "Paste the failing command and its full error." | Part 9: exit codes, 2>&1, and why the whole error matters |
"Don't curl … | sh on a production box." |
9.3 Terminal safety: what that command actually does |
| "Same command, different result on my Mac and the Linux server." | 1.3 Which shell? and 9.2: BSD vs GNU tools |
Part 1: The mental model#
1.1 Three things people call "the terminal"#
When someone says "open the terminal", three different pieces of software are involved. Separating them makes everything else easier.
flowchart LR
subgraph you ["You"]
KB["Keyboard"]
SCR["Screen"]
end
subgraph app ["Terminal emulator<br/>(Terminal, iTerm2, Windows Terminal,<br/>VS Code's integrated terminal)"]
T["Draws text,<br/>sends keystrokes"]
end
subgraph os ["Operating system"]
SH["Shell<br/>(zsh, bash, fish, PowerShell)"]
CMD["The command<br/>(ls, grep, python…)"]
end
KB --> T
T --> SH
SH --> CMD
CMD --> SH
SH --> T
T --> SCR- Terminal emulator (or just "terminal"): the window and keyboard handler. It draws characters on screen and forwards your keystrokes to a program. It doesn't understand commands itself.
- Shell: the program the terminal emulator runs that reads what you type, decides what it means, and launches other programs. On macOS and most Linux it's zsh or bash; on Windows it's PowerShell (or the older
cmd). The shell is also a programming language — that's what Part 8 is about. - Command: the program the shell launches for you —
ls,grep,git,python3,uv. When the command finishes, the shell takes back over and shows you a fresh prompt.
You can see the chain in action: type command -v zsh and it prints the shell's own path (on macOS, /bin/zsh); echo "$SHELL" shows the login shell recorded in your environment. ($0 is not the way — it holds the name the shell was invoked as, like -zsh, not a path.) Type ps -p $$ and you'll see the shell process itself. Everything else on the machine is a program the shell started.
1.2 The prompt#
The prompt is the text the shell prints to show it's ready for input — on many systems just $ , on others your name, directory and git branch:
you@macbook ~/code/ai-path (main) $ lsConventions worth knowing:
$means "type a command here as a normal user". Some docs and tutorials prefix every command with$to show it's a command, not output.>(or>>>in Python) means "the shell is waiting for more input" — you opened a quote or bracket and haven't closed it. Type the closing character, or press Ctrl+C to cancel.%is the prompt on some systems (notably the defaultcsh/tcshon older BSDs, and some custom setups).- A continuation prompt appears when a command spans several lines (after
\, or inside an open quote/if/for).
The prompt itself is customisable (it's just a shell setting), which is why yours may look different from a colleague's or a tutorial's. Don't be confused when a screenshot shows a fancier prompt — the commands are what matter.
1.3 Which shell? bash, zsh, fish, PowerShell, cmd#
A shell is a program, and there are several. They all launch the same commands (ls, grep, git are separate programs — the shell just finds and runs them), but they differ in their own syntax, startup files, and defaults.
| Shell | Where you meet it | Notes for this path |
|---|---|---|
| zsh (Z shell) | Default login shell on macOS since Catalina (2019) — Apple Support confirms "the default shell is zsh" (Apple's Terminal guide) | A bash superset with extras (better globbing, cd to a directory name without typing it, spelling correction). Its syntax for what this lesson teaches is identical to bash. As of November 2026 macOS ships zsh 5.9. |
| bash (Bourne-again shell) | Default on most Linux distributions; still present on macOS at /bin/bash — but it's the old 3.2.57 (GPLv2 licensing froze Apple's copy; check bash --version) |
The reference shell for this lesson. Everything here works in bash 3.2, bash 5.x, and zsh. Where bash 4+ has a nicer feature, the lesson says so. |
| fish (Friendly Interactive SHell) | Optional; popular with developers who want discoverable syntax | fish supports $(...) substitution, but its variable syntax differs (set instead of export, different brace-expansion rules). Not used in this path; if you use fish, the commands all work, the shell syntax in Part 8 needs translating. Current release: fish 4.9.x (fishshell.com). |
| PowerShell | The Windows shell; PowerShell 7 (pwsh) is cross-platform and current — 7.6 is the current long-term-support (LTS) release (March 2026), and the 7.5 stable line reaches end of support on 10 November 2026, as of November 2026 (Microsoft Learn) |
Not bash-compatible, but every section gives you the PowerShell equivalent. Windows PowerShell 5.1 (built into Windows) is older — prefer installing PowerShell 7 with winget install --id Microsoft.PowerShell. |
| cmd (Command Prompt) | Legacy Windows shell | You'll rarely need it; PowerShell or WSL covers everything. The path assumes you don't use it. |
| WSL (Windows Subsystem for Linux) | Not a shell — it runs a real Linux (with bash) inside Windows | The recommended route for this path on Windows: every bash command in the lesson works unchanged. Set up in 00.1. |
Which does this path use? The lesson teaches bash/zsh syntax (they're interchangeable for everything here), and gives PowerShell equivalents wherever they differ. On Windows, the cleanest route is WSL — then you run the bash commands verbatim. Native PowerShell works too; the tables cover it.
1.4 Anatomy of a command#
Every command line has the same skeleton:
command [options/flags] [arguments]
│ │ │
│ │ └─ what it acts on (files, text, URLs…)
│ └─ modifiers: -n, --line-number, -la, --recursive…
└─ the program to rungrep -n ERROR app.log
# │ │ │
# │ │ └─ argument: the file to search
# │ └─ argument: the text to find
# └─ flag -n: also print line numbersReal output:
Output:
3:2026-11-01T09:00:05Z ERROR db connection timeout after 30s
6:2026-11-01T09:00:09Z ERROR db connection timeout after 30s
8:2026-11-01T09:00:12Z ERROR auth token expired for user aliceRules of thumb:
- Flags modify how the command works. Single-letter flags can be bundled (
ls -la=-l -a); long flags use--(grep --line-number). Most commands accept both (-nand--line-number). - Arguments are what the command acts on. Order matters:
cp source dest, notcp dest source. --on its own means "everything after this is an argument, even if it starts with-" — the escape hatch for files named-rfor--help.- Flags can come before or after arguments on most commands (
grep ERROR app.log -nworks), but the convention is flags first.
1.5 Exit codes#
When a command finishes, it doesn't just produce output — it reports success or failure as a number called the exit code (or return code). The shell stores it in $?:
true; echo "true -> $?"
false; echo "false -> $?"
(exit 42); echo "custom -> $?"
ls /definitely/not/here 2>/dev/null; echo "ls missing -> $?"
echo "after a successful echo -> $?"true -> 0
false -> 1
custom -> 42
ls missing -> 1
after a successful echo -> 0The conventions (from the POSIX standard and decades of Unix practice):
| Code | Meaning |
|---|---|
0 |
Success |
1 |
General failure (the command ran but failed — file not found, no matches, bad input) |
2 |
Misuse of the command (bad flags, missing required argument) — common on GNU/Linux tools; BSD tools often use 1 instead |
126 |
Found the command but can't execute it (permission denied — the file lacks the execute bit; 6.3 shows it happening) |
127 |
Command not found (typo, or not installed/on PATH) |
128 + n |
Killed by signal n (e.g. 130 = 128+2 = killed by SIGINT, i.e. Ctrl+C) |
| anything else | The program's own choice — scripts and tools pick meaningful numbers |
Check an exit code any time with echo $? — but run it immediately after the command you care about, before anything else.
1.6 Standard input, standard output, standard error#
Every command has three channels, inherited from Unix:
flowchart LR
KB["⌨️ keyboard /<br/>another program"] -->|"stdin (0)"| PROG["your command"]
PROG -->|"stdout (1)"| OUT["screen /<br/>a file /<br/>another program"]
PROG -->|"stderr (2)"| ERR["screen /<br/>a file"]- stdin (standard input, fd 0): where the command reads input. Default: the keyboard.
- stdout (standard output, fd 1): where normal results go. Default: the screen.
- stderr (standard error, fd 2): where errors and warnings go. Default: also the screen — which is why errors and output look mixed.
Why two output channels? So a program can print results to stdout (which you can pipe into another program) while errors go to stderr (which you see but don't pipe). grep on a missing file prints its error to stderr, so grep x /nope | wc -l gives 0 — the error doesn't pollute the count.
Part 4 is entirely about redirecting and connecting these channels. The quick preview:
| Syntax | Effect |
|---|---|
cmd > file |
stdout → file (overwrites) |
cmd >> file |
stdout → file (appends) |
cmd < file |
stdin ← file |
cmd 2> file |
stderr → file |
cmd 2>&1 |
stderr → same place as stdout |
cmd > /dev/null |
stdout → nowhere (discard) |
cmd1 | cmd2 |
stdout of cmd1 → stdin of cmd2 (a pipe) |
1.7 The working directory#
The shell always has a working directory — "where you are" in the file system. Commands that take relative paths (ls notes, cat app.log) resolve them against it. pwd prints it, cd changes it.
echo '=== pwd ==='; pwd # absolute path — differs per machine
echo '=== ls ==='; ls # lists the working directory
cd projects && pwd && ls # move into ./projects, show where we are/Users/you/code/ai-path
app.log data notes tickets.json
/Users/you/code/ai-path/projects
ai-pathTwo consequences engineers learn the hard way:
cdwith no arguments goes to your home directory (~).cd -goes back to the previous directory.cd ..goes up one level.- Scripts and commands run in whatever directory you launched them from. "It works in one folder and not another" is usually a working-directory problem —
pwdis the first debugging command.
Part 2: Finding your way around the file system#
Before we explore, build the scratch folder every demo in this lesson uses — a small, realistic project so the commands always have something real to work on:
SCRATCH=$(mktemp -d) && cd "$SCRATCH" # a fresh, empty folder that is safe to experiment in
mkdir -p projects/ai-path/notes tickets/reports data/raw
printf 'buy milk\ncall dentist\n' > projects/ai-path/notes/todo.txt
printf 'first note\n' > projects/ai-path/notes/ideas.md
printf 'id,subject,status\n1,Printer broken,open\n2,VPN slow,closed\n' > tickets/tickets.csv
printf 'raw chunk 1\n' > data/raw/chunk-01.txt
printf 'raw chunk 2\n' > data/raw/chunk-02.txt
printf 'raw chunk 3\n' > data/raw/chunk-03.txt
touch .env .hidden-plan
printf 'line one\nline two\nline three\nline four\nline five\n' > five-lines.txt
printf 'alpha\nbeta\ngamma\ndelta\nepsilon\n' > greek.txt
printf 'no newline at end' > no-newline.txt
cat > app.log <<'EOF'
2026-11-01T09:00:01Z INFO server started on port 8000
2026-11-01T09:00:02Z INFO GET /health -> 200
2026-11-01T09:00:05Z ERROR db connection timeout after 30s
2026-11-01T09:00:06Z WARN retrying request 1 of 3
2026-11-01T09:00:08Z INFO GET /tickets -> 200
2026-11-01T09:00:09Z ERROR db connection timeout after 30s
2026-11-01T09:00:10Z INFO GET /health -> 200
2026-11-01T09:00:12Z ERROR auth token expired for user alice
2026-11-01T09:00:13Z INFO POST /login -> 401
EOF
cat > words.txt <<'EOF'
apple
banana
apple
cherry
banana
apple
date
EOF
cat > people.csv <<'EOF'
name,role,team
ada,engineer,platform
alan,designer,product
grace,engineer,data
linus,engineer,kernel
margaret,scientist,research
EOF
cat > tickets.json <<'EOF'
{
"request_id": "req-1042",
"tickets": [
{"id": 1, "subject": "Printer broken", "status": "open", "priority": "high", "assignee": "ada"},
{"id": 2, "subject": "VPN slow", "status": "closed","priority": "low", "assignee": "alan"},
{"id": 3, "subject": "Login loop", "status": "open", "priority": "urgent", "assignee": null},
{"id": 4, "subject": "Dark mode", "status": "open", "priority": "low", "assignee": "grace"}
],
"meta": {"page": 1, "per_page": 50, "total": 4}
}
EOF
cat > events.jsonl <<'EOF'
{"ts":"2026-11-01T09:00:01Z","level":"INFO","msg":"server started"}
{"ts":"2026-11-01T09:00:05Z","level":"ERROR","msg":"db timeout","attempt":1}
{"ts":"2026-11-01T09:00:08Z","level":"INFO","msg":"GET /tickets"}
{"ts":"2026-11-01T09:00:09Z","level":"ERROR","msg":"db timeout","attempt":2}
EOFStay in this folder for the rest of the lesson — every Output: in Parts 2–4 was produced by running these commands here, in order. Part 3 adds a few practice files; Part 4 uses the same folder for the text toolbox.
2.1 The directory tree#
Everything on your computer lives in one tree of directories (folders) and files. The root is / on macOS/Linux/WSL; on Windows each drive has a root like C:\. You navigate by naming directories relative to where you are, or absolutely from the root.
The trees look different per OS but the concepts are identical:
| Concept | macOS / Linux / WSL | Windows |
|---|---|---|
| Your home folder | /Users/you (macOS), /home/you (Linux/WSL) |
C:\Users\you |
| Path separator | / |
\ (though Windows tools accept / too) |
| Hidden files | name starts with . |
hidden attribute (Explorer's "Hidden items") |
| Case sensitivity | macOS: insensitive by default (APFS — Apple documents it as case-insensitive unless you choose the case-sensitive format). Linux and WSL's own Linux filesystem: sensitive | Insensitive by default (NTFS) |
| Case-sensitive option | macOS: APFS (Case-sensitive) volume | NTFS per-directory flag (rare) |
2.2 Absolute vs relative paths#
- Absolute path: starts at the root.
/Users/you/code/app.py,C:\Users\you\code\app.py. Unambiguous — works from anywhere, but long and machine-specific. - Relative path: starts from the working directory.
notes/todo.txt,./app.py,../shared/config.yaml. Short, portable within a project — but depends on where you are.
Three special relative names:
| Name | Means |
|---|---|
. |
this directory (e.g. ./script.sh = "the script.sh right here") |
.. |
parent directory (cd .. = up one level; ../../x = up two) |
~ |
your home directory (~/code = /Users/you/code on macOS) |
cd projects/ai-path # relative: works if ./projects exists here
cd ~/code/ai-path # absolute-via-~: works from anywhere
cd /Users/you/code/ai-path # absolute: works from anywhere, longest form2.3 pwd, ls, cd — the daily trio#
echo '=== ls: plain ==='; ls
echo '=== ls -a: show hidden files ==='; ls -a
echo '=== ls -l: long format ==='; ls -l
echo '=== ls -la: both ==='; ls -la
echo '=== ls -lh: human sizes ==='; ls -lh
echo '=== ls -lt: sort by time ==='; ls -ltls flags worth memorising (all work on macOS, Linux and WSL):
| Flag | Effect |
|---|---|
-a / --all |
include hidden files (.-prefixed) |
-l |
long format: permissions, owner, size, date |
-h |
human-readable sizes (4.0K, 2.1M) — combine with -l |
-t |
sort by modification time, newest first |
-r |
reverse the sort order |
-d |
list directories themselves, not their contents (ls -d */ lists only dirs) |
-1 |
one name per line (handy when piping) |
-F |
append / to dirs, * to executables, @ to links |
Output (real, from the demo folder — owner/dates/sizes vary per machine):
=== ls: plain ===
app.log
data
events.jsonl
five-lines.txt
greek.txt
no-newline.txt
people.csv
projects
tickets
tickets.json
words.txt
=== ls -a: show hidden files ===
.
..
.env
.hidden-plan
app.log
data
events.jsonl
five-lines.txt
greek.txt
no-newline.txt
people.csv
projects
tickets
tickets.json
words.txtls -l adds permissions/owner/size/date columns, -la combines it with hidden files, -lh shows 4.0K-style sizes, -lt sorts newest-first. (Owner names, dates and exact sizes differ on your machine — that's expected.)
cd variants:
cd # home directory
cd ~ # same, explicit
cd - # previous directory (great for hopping between two folders)
cd .. # up one level
cd ../.. # up two levels
cd projects/ai-path/notes # any relative or absolute path2.4 Hidden files#
On macOS/Linux a file is hidden when its name starts with a dot: .env, .gitignore, .zshrc, .hidden-plan. They're hidden from plain ls because they're almost always configuration, and you rarely want them cluttering a listing — but they're not secret or protected, just conventionally out of sight.
touch .env .hidden-plan
ls # neither appears
ls -a # both appear, plus . and ..
ls -A # hidden files, but not . and ..
cat .env # you can still read/write them directly.env files will matter enormously later — they hold API keys. The dot is exactly why git status doesn't show them by default and why .gitignore exists (00.3, 03.1 §3.4).
2.5 Tab completion, history, clear#
- Tab completion: press
Tabto complete a command or file name.ls proj⇥→projects/. PressTabtwice to list candidates. This is the single biggest speedup in the terminal — use it constantly, it also prevents typos in paths. - History: every command is remembered.
historylists it (in zsh and bash;↑/↓arrows step through it).!!repeats the last command,!greprepeats the last command starting withgrep,Ctrl+Ropens reverse history search — type a few letters and it finds the last matching command. clear(orCtrl+L) wipes the screen. Nothing is lost — it's cosmetic; scrollback in your terminal app still has it.
2.6 Globbing (wildcards)#
Before the shell runs a command, it expands wildcards in the arguments into matching file names. This is called globbing (or pathname expansion):
| Pattern | Matches |
|---|---|
* |
any characters, including none (*.txt, app*) |
? |
exactly one character (file?.txt → file1.txt, fileA.txt) |
[abc] |
one character from the set (file[0-9].txt) |
{a,b,c} |
brace expansion: literally a, b, c — mkdir {reports,drafts} makes two dirs |
** |
recursive (in bash with globstar, zsh by default) |
Real example:
mkdir -p {reports,drafts,archive}
ls -d */
ls *.txt
ls t?ckets*Output:
archive/
data/
drafts/
projects/
reports/
tickets/
five-lines.txt
greek.txt
no-newline.txt
words.txt
tickets.json
tickets:
reports
tickets.csvTwo subtleties in that output:
ls t?ckets*matched the directoryticketsand the filetickets.json.lson a directory lists its contents (that's thetickets:section), while on a file it prints the name. Add-dto see the names themselves:ls -d t?ckets*.- Brace expansion
{a,b}is a shell feature, not a command feature — it works in bash, zsh and fish; plain POSIXsh(likedash) doesn't do it. It happens before the command runs.
2.7 Spaces and quoting#
File names can contain spaces — my project/read me.txt — but a space also separates arguments. So ls my project is parsed as two arguments: my and project, not one name with a space.
mkdir -p "my project"
touch "my project/read me.txt"
ls my* # the * matched the whole directory name
echo '--- unquoted ---'
ls my project # ERROR: two argumentsOutput:
read me.txt
--- unquoted ---
ls: my: No such file or directory
ls: project: No such file or directory(ls my* printed read me.txt — the contents of the matched directory, per the ls-on-a-directory rule above.)
The fix is quoting: wrap the name in double quotes "my project" or single quotes 'my project', or escape each space with a backslash my\ project. The difference between the two quote types matters for variables — that's 8.2.
Rule of thumb: quote anything that could contain a space, and quote variables ("$dir/file.txt"), because an unquoted $dir containing a space splits into two arguments.
Part 3: Files and folders#
Stay in the same scratch folder — and keep the same rule: never practise rm in your real folders. Add a few tiny practice files for the file commands:
printf 'hello\nworld\n' > greeting.txt
printf 'one two three\nfour five\n' > counts.txt
seq 1 5 > nums.txt
printf '\x89PNG' > fake.png # not a real PNG — just bytes with a .png name
touch empty.txt notes.mdEverything below ran inside such a scratch folder. The commands are identical everywhere.
3.1 Creating: mkdir, touch#
mkdir notes # one directory
mkdir -p demo/a/b/c # -p: create parents as needed, no error if it exists
touch empty.txt notes.md # create empty files (or refresh timestamps on existing ones)
find demo -type d | sort # prove the whole chain was createdOutput:
demo
demo/a
demo/a/b
demo/a/b/cmkdir -p is the safe default: it succeeds whether or not the directory already exists, and builds the whole chain. Without -p, mkdir a/b/c fails if a/b doesn't exist.
3.2 Copying and moving: cp, mv#
cp greeting.txt greeting-copy.txt # copy file -> new name
mkdir -p src/sub && printf 'x\n' > src/sub/deep.txt
cp -r src dst # -r: recursive, copies whole trees
mv greeting-copy.txt renamed.txt # mv renames
mv notes.md notes/ # or moves into another directory
find dst | sort # prove the tree was copiedOutput:
dst
dst/sub
dst/sub/deep.txtUseful flags: cp -i/mv -i ask before overwriting (some distros alias these on by default), cp -v/mv -v print what they did, cp -p preserves timestamps.
3.3 Reading files: cat, less, head, tail#
echo '=== cat ==='; cat greeting.txt # print whole file to stdout
less app.log # interactive pager: space=next page, /search, q=quit
echo '=== head -3 ==='; head -3 nums.txt # first lines (default 10)
echo '=== tail -2 ==='; tail -2 nums.txt # last lines
tail -f app.log # follow: keep printing new lines as they're appended (Ctrl+C stops it) — THE log-watching commandOutput:
=== cat ===
hello
world
=== head -3 ===
1
2
3
=== tail -2 ===
4
5less is the pager you'll live in: Space/f page down, b page up, /pattern search, n/N next/previous match, q quit, G end, g start. (more is the older, weaker version; prefer less.)
tail -f deserves emphasis: it's how you watch a server log, a training run, or docker logs in real time. tail -F (capital) additionally follows the file if it's rotated/recreated — the production-grade choice for logs that get renamed.
3.4 Counting and measuring: wc, file, du, df#
echo '=== wc counts.txt ==='; wc counts.txt # lines words bytes
echo '=== wc -l ==='; wc -l counts.txt # just lines — the most common use
echo '=== wc -w ==='; wc -w counts.txt # words
echo '=== wc -c ==='; wc -c counts.txt # bytes
echo '=== file ==='; file greeting.txt nums.txt fake.png # what kind of file is this?
du -sh . # disk usage of this folder, human-readable
df -h # free space on all mounted filesystemsOutput:
=== wc counts.txt ===
2 5 24 counts.txt
=== wc -l ===
2 counts.txt
=== wc -w ===
5 counts.txt
=== wc -c ===
24 counts.txt
=== file ===
greeting.txt: ASCII text
nums.txt: ASCII text
fake.png: Non-ISO extended-ASCII text, with no line terminators # despite the .png name!Example output (illustrative — sizes vary per machine and filesystem):
84K .
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk3s1 460Gi 12Gi 220Gi 6% 356k 2.3G 0% /file reads the file's magic bytes, not its extension — a file named fake.png containing text is reported as text. That's why "the file won't open" is sometimes a mislabeled download. (The exact wording and the wc column padding are the macOS/BSD forms: GNU file describes the four-byte fake.png as data, and GNU wc prints numbers without the leading spaces.)
du/df sizes vary per machine and filesystem — treat them as illustrative magnitudes.
3.5 Deleting safely: rm, rm -r#
rm renamed.txt # delete the copy we made — permanent, no trash, no undo
ls renamed.txt # -> proof it's really goneOutput:
ls: renamed.txt: No such file or directoryFor empty directories use rmdir (fails if non-empty — a built-in safety check). For non-empty, rm -r.
3.6 Links: ln (awareness)#
ln -s greeting.txt link-to-greeting # symbolic link (symlink): a pointer file
ln greeting.txt hardlink-to-greeting # hard link: another name for the same data (rarer)
ls -l link-to-greeting | awk '{print $1, $9, $10, $11}' # mode name -> target (owner/date vary)
readlink link-to-greeting # prints the target
cat link-to-greeting # reads through the linkOutput:
lrwxr-xr-x link-to-greeting -> greeting.txt
greeting.txt
hello
worldA symlink is a small file containing a path; deleting it doesn't delete the target, but deleting/moving the target breaks it. You'll meet symlinks in node_modules, virtualenvs, and ln -s tricks for config. A hard link is a second directory entry for the same inode — edits via either name change the same data; deleting one name keeps the data until the last link goes.
3.7 Opening files from the terminal#
open file.txt # macOS: opens in default app
xdg-open file.txt # Linux
start file.txt # Windows (cmd); Invoke-Item file.txt in PowerShell
code file.txt # VS Code, if installed (code is on PATH after install)open/xdg-open/start are the "double-click" of the terminal — handy in scripts and when an error message gives you a path.
3.8 Comparing, packaging and the clipboard (awareness)#
Three more small tools you'll meet constantly — awareness level is enough today:
-
diffcompares two files line by line and prints what differs; it exits1when they differ (and0when identical — itself an exit-code check).diff -uproduces unified format, the@@hunks you see ingit diffand patch files. For a friendlier view,vimdiff a borcode --diff a bopens a side-by-side.bash printf 'a\nb\nc\n' > v1.txt; printf 'a\nB\nc\n' > v2.txt diff v1.txt v2.txt # line-oriented report diff -u --label a/v1.txt --label b/v2.txt v1.txt v2.txt # unified, clean labels (no timestamps)text Output: 2c2 < b --- > B --- a/v1.txt +++ b/v2.txt @@ -1,3 +1,3 @@ a -b +B c(
--labelreplaces the filename-and-timestamp header lines so the output is reproducible; plaindiff -uprints--- v1.txt\t<timestamp>instead.) You'll usediffto compare config files, generated output, and "what changed between these two runs" —git diffis the same idea for versioned files. -
tarbundles many files into one archive file — the.tar/.tar.gzyou download for model weights, datasets and release bundles. The flags decode as:-ccreate,-xextract,-tlist,-zgzip-compress,-fthe archive file,-Cchange directory first,-vverbose.bash mkdir -p bundle-src/reports unpacked printf 'q3 numbers\n' > bundle-src/reports/q3.txt printf 'release notes\n' > bundle-src/README.txt tar -czf bundle.tar.gz -C bundle-src . # create a gzipped tarball of the tree tar -tzf bundle.tar.gz | sort # list contents without extracting tar -xzf bundle.tar.gz -C unpacked # extract into a fresh directory find unpacked -type f | sort # prove it round-trippedtext Output: ./ ./README.txt ./reports/ ./reports/q3.txt unpacked/README.txt unpacked/reports/q3.txtThe
-C dirtrick keeps stored paths relative to that folder — without it,tar -czf bundle.tar.gz bundle-srcwould store every path with abundle-src/prefix, and extracting would recreate that extra folder level (tar strips a leading/from absolute paths, but the prefix you typed is kept).zip/unzipis the Windows-friendly equivalent;taris the Unix-native one. -
Scheduling (awareness only): recurring jobs run via
cronon Linux servers (crontab -eedits your schedule,crontab -llists it),launchdon macOS, Task Scheduler on Windows, or systemd timers on modern distros. You won't configure these in this path, but "why did this job run at 03:00?" is a debugging question you'll meet on real infrastructure. -
Clipboard tools: pipe command output straight to the clipboard instead of copy-pasting selected text —
pbcopy/pbpasteon macOS,xclip/xsel(X11) orwl-copy/wl-paste(Wayland) on Linux,cliporSet-Clipboardin PowerShell:bash grep ERROR app.log | pbcopy # the error lines are now on your clipboard pbpaste | grep -c ERROR # …and you can pipe the clipboard back inHandy for "copy this path/error/JSON into Slack or a bug report" without selecting it by hand.
Part 4: Pipes, redirection and the text toolbox#
This is the part that makes the terminal feel like a superpower. The idea is small: every command reads stdin and writes stdout, so you can chain them. Small tools that each do one thing well, connected by pipes, beat one big tool that does everything badly.
Our running example is app.log — a web server's log with INFO, WARN and ERROR lines — plus words.txt, people.csv, tickets.json and events.jsonl. We're still in the same scratch folder, which now also holds the files Parts 2–3 created (greeting.txt, counts.txt, nums.txt, src/, dst/, demo/…). That's deliberate — 4.5's find will show you exactly how much it searches.
4.1 Pipes: cmd1 | cmd2#
A pipe | connects cmd1's stdout to cmd2's stdin. cmd1 doesn't know or care where its output goes; cmd2 doesn't care where its input comes from.
echo '=== count ERROR lines ==='; grep ERROR app.log | wc -l
echo '=== first warnings ==='; cat app.log | grep WARN | head -3
echo '=== word frequencies ==='; sort words.txt | uniq -cOutput:
=== count ERROR lines ===
3
=== first warnings ===
2026-11-01T09:00:06Z WARN retrying request 1 of 3
=== word frequencies ===
3 apple
2 banana
1 cherry
1 dateReading a pipeline left to right: take the log, keep the ERROR lines, count them. Each stage transforms the stream. This is the same idea as a data pipeline in Python (df[df.x > 0]) or an ETL job — you're filtering and shaping text as it flows through.
4.2 Redirection: >, >>, <, 2>, 2>&1, /dev/null#
Pipes connect commands to each other; redirection connects them to files (or nowhere):
echo '=== > writes (overwrites) ==='; grep ERROR app.log > errors.txt; wc -l errors.txt
echo '=== > truncates, >> appends ==='
printf 'stale line\n' > scan.log; printf 'fresh scan\n' > scan.log; cat scan.log # 'stale line' is gone
printf 'second pass\n' >> scan.log; cat scan.log # appended, not replaced
echo '=== stderr -> file ==='; ls /definitely/not/here 2> err.txt; echo "exit=$?"; cat err.txt
echo '=== 2>&1 merges stderr into stdout ==='; { ls /definitely/not/here; echo 'still running'; } 2>&1; echo "exit=$?"
echo '=== 2>/dev/null discards stderr ==='; ls /definitely/not/here 2>/dev/null; echo "after: $?"
ls /definitely/not/here 2>&1 | grep -c 'No such' # stderr piped: the error text reaches grepOutput:
=== > writes (overwrites) ===
3 errors.txt
=== > truncates, >> appends ===
fresh scan
fresh scan
second pass
=== stderr -> file ===
exit=1
ls: /definitely/not/here: No such file or directory
=== 2>&1 merges stderr into stdout ===
ls: /definitely/not/here: No such file or directory
still running
exit=0
=== 2>/dev/null discards stderr ===
after: 1
1The subtle one is 2>&1: it means "make stderr go to the same place stdout currently goes". Order matters — cmd 2>&1 > file sends stderr to the old stdout (screen) and stdout to the file; cmd > file 2>&1 sends both to the file. When in doubt, write > file 2>&1 in that order.
/dev/null is the operating system's "bit bucket" — a file that discards everything written to it. 2>/dev/null silences errors; >/dev/null silences output; &>/dev/null silences both (bash shorthand for >/dev/null 2>&1). On Windows PowerShell the equivalent is $null or Out-Null.
4.3 tee, xargs, command substitution#
-
tee: copies stdin to stdout and a file — "look at it and save it".bash grep ERROR app.log | tee errors2.txt | wc -l # shows count AND saves the lines diff errors.txt errors2.txt && echo 'files identical' rm errors.txt err.txt errors2.txt scan.log # tidy up the Part-4 demo files -
xargs: builds command lines from stdin — "run this command once per input (or batched)".bash printf 'alpha\nbeta\ngamma\n' | xargs echo # -> alpha beta gamma find . -maxdepth 1 -name '*.txt' -print0 | xargs -0 wc -l-0/--nullpairs withfind -print0so filenames containing spaces survive — the safe pattern. Without it,xargssplits on whitespace and a file namedmy report.txtbecomes two arguments. (Awareness level: you'll seexargsin build scripts andfind … -deletereplacements; you don't need to master it today.) -
Command substitution
$(...): runs a command and inserts its output as text.`...`(backticks) is the old form.bash echo "there are $(grep -c ERROR app.log) ERROR lines" # -> there are 3 ERROR lines echo "upper: $(echo hello | tr a-z A-Z)" # -> upper: HELLOThe output is text, not data —
$(ls)gives filenames as words. For anything non-trivial, a shell script or Python is clearer (Part 8).
4.4 grep — find lines matching a pattern#
grep is the workhorse: print lines matching a regular expression.
| Flag | Effect | Example |
|---|---|---|
-i |
case-insensitive | grep -i error app.log |
-n |
prefix line numbers | grep -n ERROR app.log |
-v |
invert: lines that don't match | grep -v ERROR app.log |
-c |
count only | grep -c ERROR app.log → 3 |
-E |
extended regex (alternation |, +, ?, ()) |
grep -E 'ERROR|WARN' app.log |
-r / -R |
recursive through directories | grep -rn TODO src/ |
-l |
filenames only | grep -rl secret . |
-w |
whole-word match | grep -w ERROR app.log |
-A/-B/-C n |
n lines after/before/context | grep -C2 ERROR app.log |
-o |
only the matched part | grep -oE '[0-9]+' app.log |
printf 'Info line\ninfo line\nINFO line\n' > case.txt # the mixed-case file for -i
grep ERROR app.log # the 3 error lines
grep -n ERROR app.log # same, with line numbers
grep -c ERROR app.log # 3
grep -v ERROR app.log # everything else
grep -i info case.txt # Info/info/INFO all match
grep -E 'ERROR|WARN' app.log # alternationThe regex flavour differs subtly between BSD grep (macOS) and GNU grep (Linux) for exotic patterns, but ^, $, ., *, [], (), |, +, ? all work everywhere with -E. For heavy regex work, tools like ripgrep (rg) are faster and saner — mention only, not required.
4.5 find — find files by name, type, date, size#
grep searches file contents; find searches the file system.
find . -name '*.txt' # files ending .txt under here
find . -name '*.txt' | sort # sorted (find order isn't sorted!)
find . -type f -name '*.json*' # only regular files
find . -type d -name 'node_modules' # only directories
find . -size +1M # bigger than 1 MB
find . -mtime -7 # modified in last 7 days
find . -name '*.log' -delete # delete matches — CAREFUL, test with ls firstReal output (from the scratch tree):
$ find . -name '*.txt' | sort
./bundle-src/README.txt
./bundle-src/reports/q3.txt
./case.txt
./counts.txt
./data/raw/chunk-01.txt
./data/raw/chunk-02.txt
./data/raw/chunk-03.txt
./dst/sub/deep.txt
./empty.txt
./five-lines.txt
./greek.txt
./greeting.txt
./my project/read me.txt
./no-newline.txt
./nums.txt
./projects/ai-path/notes/todo.txt
./src/sub/deep.txt
./unpacked/README.txt
./unpacked/reports/q3.txt
./v1.txt
./v2.txt
./words.txt
$ find . -type f -size +0c -name '*.json*' | sort
./events.jsonl
./tickets.json⚠️ find . -name '*.txt' also descended into my project/, data/raw/, bundle-src/ and unpacked/ — it searches everything below .. Narrow with -maxdepth 1 or a more specific path. And -delete/-exec rm are destructive: run the same find without the action first to see what it would hit.
4.6 sort, uniq, cut, tr#
echo '=== sort | uniq -c ==='; sort words.txt | uniq -c # count each unique line (uniq needs sorted input!)
echo '=== sort -u ==='; sort -u words.txt # unique lines only
printf '10\n9\n100\n2\n' > nums-unsorted.txt
echo '=== sort -nr ==='; sort -nr nums-unsorted.txt # numeric sort, reverse
echo '=== sort CSV by column 2 ==='; sort -t, -k2,2 people.csv
echo '=== cut fields ==='; cut -d, -f1 people.csv; cut -d, -f1,3 people.csv | head -3
echo '=== tr ==='; printf 'hello world\n' | tr 'a-z' 'A-Z'; printf 'a b c\n' | tr -s ' '; printf 'remove-dashes\n' | tr -d '-'Output:
=== sort | uniq -c ===
3 apple
2 banana
1 cherry
1 date
=== sort -u ===
apple
banana
cherry
date
=== sort -nr ===
100
10
9
2
=== sort CSV by column 2 ===
alan,designer,product
ada,engineer,platform
grace,engineer,data
linus,engineer,kernel
name,role,team
margaret,scientist,research
=== cut fields ===
name
ada
alan
grace
linus
margaret
name,team
ada,platform
alan,product
=== tr ===
HELLO WORLD
a b c
removedashesThe classic beginner bug: uniq only removes adjacent duplicates, so sort | uniq is the idiom — sort first, then dedupe/count. cut splits on a delimiter (-d,) and picks fields (-f1,3); it's line-oriented and dumb about quoting (a CSV field containing a comma breaks it — that's what a real CSV parser is for, later in Python).
4.7 sed basics, awk taste#
sed (stream editor) applies edit commands to each line:
sed 's/ERROR/CRITICAL/' app.log # substitute first occurrence per line -> stdout
sed 's/ERROR/CRITICAL/g' app.log # /g: all occurrences
sed -n '2,4p' app.log # print only lines 2-4
sed -i '' 's/old/new/' file.txt # -i: edit in place — NOTE the '' on macOS/BSD!
sed -i 's/old/new/' file.txt # GNU/Linux form (no '')awk is a whole little language for columnar text — worth a taste, not a chapter:
echo '=== sed substitute ==='; sed 's/ERROR/CRITICAL/' app.log | head -3
echo '=== sed line range ==='; sed -n '2,4p' app.log
echo '=== awk field 1, skip header ==='; awk -F, 'NR>1 {print $1}' people.csv
echo '=== awk histogram, biggest first ==='; awk '{print $3}' app.log | sort | uniq -c | sort -rn(sed -i '' 's/old/new/' file.txt on macOS / sed -i 's/old/new/' file.txt on Linux edits in place — syntax shown, not run here.)
Output:
=== sed substitute ===
2026-11-01T09:00:01Z INFO server started on port 8000
2026-11-01T09:00:02Z INFO GET /health -> 200
2026-11-01T09:00:05Z CRITICAL db connection timeout after 30s
=== sed line range ===
2026-11-01T09:00:02Z INFO GET /health -> 200
2026-11-01T09:00:05Z ERROR db connection timeout after 30s
2026-11-01T09:00:06Z WARN retrying request 1 of 3
=== awk field 1, skip header ===
ada
alan
grace
linus
margaret
=== awk histogram, biggest first ===
3 GET
2 db
1 server
1 retrying
1 POST
1 auth-F, sets the field separator; $1, $2… are fields; NR is line number; print emits. awk shines on logs and CSV-ish data, but the moment you need real parsing (JSON, quoting, types), that's Python's job — which is exactly what 01A teaches.
4.8 jq for JSON#
APIs speak JSON, logs are often JSON, config files are JSON. jq is the grep of the JSON world: it parses JSON and lets you pull out exactly the pieces you want. Install it per the Setup (brew install jq; as of November 2026 upstream is at 1.8.x, macOS may ship jq-1.7.1-apple).
tickets.json (abridged):
{"request_id": "req-1042",
"tickets": [
{"id": 1, "subject": "Printer broken", "status": "open", "priority": "high", "assignee": "ada"},
{"id": 3, "subject": "Login loop", "status": "open", "priority": "urgent", "assignee": null}],
"meta": {"page": 1, "total": 4}}The mental model: jq '<filter>' file.json — the filter is a little expression that walks the JSON tree. . is "the whole thing"; .field descends; [] iterates arrays; | pipes values through more filters (same idea as the shell pipe!).
jq '.request_id' tickets.json # "req-1042"
jq '.tickets | length' tickets.json # 4
jq '.tickets[].subject' tickets.json # each subject
jq '.tickets[] | select(.status == "open") | .subject' tickets.json
jq '.meta.total' tickets.json # 4 — a scalar, not an array
jq -r '.tickets[] | "\(.id): \(.subject) [\(.priority)]"' tickets.json # -r raw strings, \() interpolation
jq '[.tickets[] | select(.assignee == null)] | length' tickets.json # count unassigned
jq -c '.tickets[0]' tickets.json # -c compact (one line)Output:
"req-1042"
4
"Printer broken"
"VPN slow"
"Login loop"
"Dark mode"
"Printer broken"
"Login loop"
"Dark mode"
4
1: Printer broken [high]
2: VPN slow [low]
3: Login loop [urgent]
4: Dark mode [low]
1
{"id":1,"subject":"Printer broken","status":"open","priority":"high","assignee":"ada"}And on JSON Lines (one JSON object per line — the format API logs, eval results and trace stores use):
jq -r 'select(.level == "ERROR") | .msg' events.jsonl # db timeout\ndb timeout
jq -s 'length' events.jsonl # -s: slurp lines into one array -> 4Why this matters later: 11A.1 stores LLM traces as JSONL "queryable with jq", and 03.1 uses curl … | jq to inspect API responses by hand. jq is the difference between "here's 4 KB of JSON, good luck" and .choices[0].message.content.
Part 5: Environment variables, PATH and dotfiles#
5.1 Two kinds of variables#
The shell lets you store values in variables. There are two kinds, and the difference is who can see them:
- Shell variable: visible only inside the current shell.
MY_VAR=hello. - Environment variable: passed to every program the shell launches — children inherit a copy. Created with
export.
MY_VAR=hello
echo "MY_VAR=$MY_VAR" # -> MY_VAR=hello
sh -c 'echo "child sees: [${MY_VAR:-<unset>}]"' # -> child sees: [<unset>] — MY_VAR was never exported!
export MY_VAR=hello
sh -c 'echo "child sees: ${MY_VAR}"' # -> child sees: hello
env | grep '^MY_VAR=' # -> MY_VAR=hello
printenv MY_VAR # -> hello
unset MY_VAR
printenv MY_VAR || echo "(unset)" # -> (unset)Why it matters: when Python (or any program) asks "what's the API key?", it's reading its environment — the variables its parent process handed down. That's the whole mechanism behind .env files and os.environ in 01B.2.
5.2 Reading and setting variables#
export NAME=value # create/update an environment variable
NAME=value # shell variable only (no export)
echo $NAME # expand it
echo ${NAME:-default} # use default if unset/empty
echo ${NAME:?error msg} # fail with message if unset — used in scripts
env # list ALL environment variables (name=value, in arbitrary order)
env | sort # sorted list
env | grep API # find variables with API in the name
printenv NAME # print one variable's value (exit 1 if unset)
set | less # everything: shell vars + functions + env (overwhelming — use sparingly)
unset NAME # deleteQuoting rules for expansion:
WHO=world
echo "double: hello $WHO" # -> double: hello world (expands)
echo 'single: hello $WHO' # -> single: hello $WHO (literal)
echo "braces: hello ${WHO}!" # -> braces: hello world! (needed before punctuation)Double quotes expand variables but preserve spaces as one argument; single quotes are fully literal. Always "$VAR" — never $VAR bare — unless you want word splitting.
5.3 PATH and finding programs#
PATH is the most important environment variable: a colon-separated (: on macOS/Linux, ; on Windows) list of directories the shell searches, left to right, when you type a command name.
echo "$PATH" | tr ':' '\n' | head -5 # one directory per line
command -v ls # where the shell finds ls
command -v python3 # where python3 lives
which ls # older equivalent of command -vOutput (paths differ per machine — illustrative):
/Users/you/.local/bin
/opt/homebrew/bin
/usr/local/bin
/usr/bin
/bin
...
/bin/ls
/opt/homebrew/bin/python3
/bin/lsWhen you type ls, the shell checks each PATH directory in order for an executable named ls, and runs the first hit. command -v (preferred over which — it's a shell builtin, always available, and also finds aliases/functions) tells you which one it found.
Adding a folder to PATH (the fix for "installed but not found"): put an export line in your shell's startup file and reload it. Put your folder first so it wins over older copies, and keep the existing value with $PATH:
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # zsh (macOS default); use ~/.bashrc for bash
source ~/.zshrc # re-read the file in this shell
command -v uv # should now print a pathThe single quotes matter: they stop the shell expanding $HOME and $PATH now, so the literal text lands in the file and is expanded afresh every time a new shell starts. Putting the folder last instead (export PATH="$PATH:/new/folder") means an existing program of the same name wins. On native Windows, use Settings → System → About → Advanced system settings → Environment Variables (or setx) and open a new terminal afterwards.
The PATH trap that bites AI engineers: two Pythons, two uvs, two nodes. command -v python3 shows which one wins; the first PATH entry shadows the rest. Version managers (uv, pyenv, nvm) work by prepending their directory to PATH.
5.4 Startup files and dotfiles#
Your shell reads dotfiles (hidden config files in ~) at startup. Which ones depends on the shell and whether it's a login shell (what you get when you open a terminal or SSH in) or an interactive non-login shell:
| File | Read by | When |
|---|---|---|
~/.zshenv |
zsh | every zsh invocation (even scripts) — keep it minimal |
~/.zprofile |
zsh | login shells only |
~/.zshrc |
zsh | interactive shells (your aliases, PATH tweaks, prompt go here) |
~/.zlogin |
zsh | login shells, after .zshrc |
~/.bash_profile |
bash | login shells (macOS default order checks this first) |
~/.bash_login |
bash | login shells (only if .bash_profile absent) |
~/.profile |
bash/sh | login shells (fallback; sourced by some display managers) |
~/.bashrc |
bash | interactive non-login shells (and often sourced from .bash_profile) |
~/.config/fish/config.fish |
fish | interactive shells |
~/.config/powershell/Microsoft.PowerShell_profile.ps1 |
PowerShell | every PowerShell session (Windows: ~\Documents\PowerShell\Microsoft.PowerShell_profile.ps1; Windows PowerShell 5.1 uses WindowsPowerShell\ instead) |
Reloading your dotfiles. After editing .zshrc/.bashrc, you don't need a new terminal: source ~/.zshrc (or . ~/.zshrc — the dot is short for source) re-reads the file into the current shell, so new aliases and PATH entries take effect immediately. source runs the file's commands in the current shell rather than a child — it's the single most common dotfile command.
Shell aliases live in dotfiles too — alias ll='ls -la' makes ll a shortcut (8.6 covers them).
5.5 From the shell to Python: os.environ#
The bridge to the rest of the path: Python reads the same environment. In 01B.2 you'll do this properly with pydantic-settings; here's the raw mechanism:
# preview_env.py — run: export AI_PATH_GREETING='hello from the shell' && python3 preview_env.py
import os
print(os.environ.get("AI_PATH_GREETING", "<unset>")) # hello from the shell
print("HOME is set:", "HOME" in os.environ) # TrueOutput:
hello from the shell
HOME is set: TrueSo export OPENAI_API_KEY=... in your shell → Python's os.environ["OPENAI_API_KEY"] → the SDK picks it up automatically. The .env file is just a text file that tools like python-dotenv or uv run --env-file load into this environment before Python starts (03.1 §3.4). The shell is where the environment is born.
Part 6: Permissions, processes and ports#
Deep-dive
6.1 Permission bits: rwx#
Every file and directory has three permission bits for each of three audiences — user (owner), group, others:
| Bit | On a file | On a directory |
|---|---|---|
r (read, 4) |
read contents | list names (ls) |
w (write, 2) |
modify contents | create/delete entries inside |
x (execute, 1) |
run as a program | enter/traverse (cd) |
ls -l shows them as rwxr-xr-x — nine chars: owner/group/other. The first char is the file type (- file, d dir, l symlink). chmod changes them:
printf 'echo hi\n' > plain.sh # the file the chmod demos below act on
mkdir private_dir dir # scratch dirs for the directory examples
show() { ls -l plain.sh | awk '{print "mode:", $1}'; } # tiny helper: print just the mode column
ls -l plain.sh # full long listing: mode, links, owner, group, size, date, name
show
chmod u+x plain.sh; show # symbolic: add execute for owner
chmod 755 plain.sh; show # octal: 7=rwx owner, 5=r-x group, 5=r-x other
chmod 644 plain.sh; show # 6=rw- owner, 4=r-- group, 4=r-- other
chmod 700 private_dir/ # owner-only everything — directories take the same modes
chmod -R 755 dir/ # -R recursive — CAREFUL: changes everything inside dir/
# chmod 600 ~/.ssh/id_ed25519 # the real-world idiom: owner-only read/write for a private key
# # (commented out: you only have this file after the SSH setup in 00.4)Octal cheat: r=4 w=2 x=1, sum per audience. 755 = rwx r-x r-x (owner full, others read+run — normal for scripts/programs). 644 = rw- r-- r-- (normal for data files). 600 = rw- --- --- (private files: keys, .env).
Real output from a scratch file (the first line is the plain ls -l, the rest are the show calls in order):
Output:
-rw-r--r-- 1 you staff 8 Nov 6 16:16 plain.sh # ls -l (owner name varies)
mode: -rw-r--r-- # ls -l | awk '{print $1}'
mode: -rwxr--r-- # after chmod u+x
mode: -rwxr-xr-x # after chmod 755
mode: -rw-r--r-- # after chmod 644Directories need x to be entered and r to be listed — see it happen:
mkdir -p vault && printf 'secret\n' > vault/inner.txt
chmod 000 vault
ls vault # -> Permission denied, even for the owner
chmod 700 vault
ls vault # -> inner.txtOutput:
ls: vault: Permission denied
inner.txt6.2 Ownership and sudo#
Every file has an owner and group (ls -l columns 3–4). whoami prints your username, id prints uid/gid/groups, id -u just the numeric user id.
sudo (superuser do) runs a command as root — the all-powerful admin account. Rules:
- Use it only when a command genuinely needs it: installing system packages (
apt,brewsometimes), binding ports <1024, editing/etc,chowning files you don't own. - It will ask for your password — that's normal. If
sudosays "user is not in the sudoers file", you don't have admin rights; ask whoever manages the machine. - Never
sudosomething you don't understand, neversudoa script you downloaded, never make a habit ofsudo python script.py(it creates root-owned files in your project — the classic "permission denied" loop). - On macOS,
sudotriggers Touch ID or a password dialog depending on config; on Linux it's the password.
Windows 11 (24H2 and later) ships an optional Sudo for Windows feature — off by default, enabled in Settings > System > Advanced > Enable sudo, with three modes (new window, input closed, inline; Microsoft Learn). On older Windows, admin rights are per-app ("Run as administrator") or an elevated shell; runas exists but is limited. In WSL you're back in Unix-land and sudo works normally. For this path, sudo matters mainly on Linux servers later.
6.3 Executable scripts and the shebang#
To run a script as ./script.sh (rather than bash script.sh), two things are needed: the execute bit and a shebang telling the kernel which interpreter to use.
printf '#!/bin/sh\necho hi\n' > plain.sh # a script WITH a shebang
chmod 644 plain.sh
./plain.sh # -> Permission denied, exit=126 (no x bit)
bash plain.sh # -> hi, exit=0 (works without x!)
chmod 755 plain.sh
./plain.sh # -> hi
printf 'echo no-shebang\n' > noshebang.sh && chmod 755 noshebang.sh
./noshebang.sh # -> no-shebang anyway! bash/zsh fall back to running it as a shell scriptThe shebang #! on line 1 names the interpreter:
#!/bin/bash # run with bash specifically
#!/bin/sh # run with sh (POSIX — most portable)
#!/usr/bin/env bash # find bash on PATH — preferred when bash isn't at /bin/bash
#!/usr/bin/env python3 # same trick for Python scripts/usr/bin/env is the portable idiom: it looks up the program on PATH, so the script works even if bash lives at /opt/homebrew/bin/bash instead of /bin/bash. On macOS /bin/bash is the ancient 3.2 — for modern bash features use #!/usr/bin/env bash with a Homebrew bash, or just target bash-3.2-compatible syntax (this lesson does).
6.4 Processes: ps, top, kill, signals#
A process is a running program. The shell itself is one; every command you run is a child process.
ps aux | head -10 # all processes (works on macOS and Linux; 'ps -ef' is the older SysV form)
ps -p $$ # info about the current shell's PID
pgrep -fl python # find processes matching 'python'
top # live process viewer (htop is the nicer one: brew install htop)To stop a process: kill sends it a signal — a numbered message. The common ones:
| Signal | # macOS/BSD | # Linux | Name | Effect |
|---|---|---|---|---|
| SIGINT | 2 | 2 | Interrupt | "please stop" — what Ctrl+C sends |
| SIGTERM | 15 | 15 | Terminate | "please exit cleanly" — the polite default for kill |
| SIGKILL | 9 | 9 | Kill | "die immediately, no cleanup" — use only when SIGTERM fails |
| SIGHUP | 1 | 1 | Hangup | "your terminal went away" — often reload-or-die |
| SIGSTOP | 17 | 19 | Stop | freeze immediately; cannot be caught or ignored |
| SIGTSTP | 18 | 20 | Stop | "pause" — what Ctrl+Z sends |
| SIGCONT | 19 | 18 | Continue | resume a stopped job |
Signal numbers are not portable — the first four coincide everywhere, but the job-control trio differs between macOS/BSD and Linux. kill -l lists your platform's own numbering (below).
kill 1234 # SIGTERM to PID 1234
kill -9 1234 # SIGKILL — last resort
kill -l # list all signal names/numbers (macOS shows BSD names like SIGEMT; Linux differs slightly)
kill -TERM -1234 # signal a whole process GROUP (negative pid) — advancedOutput (macOS, bash's kill -l, first signals — yours may differ slightly; zsh, the macOS default shell, prints bare names without numbers):
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGEMT 8) SIGFPE
9) SIGKILL 10) SIGBUS 11) SIGSEGV 12) SIGSYS
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGURG
17) SIGSTOP 18) SIGTSTP 19) SIGCONT 20) SIGCHLD6.5 Jobs: foreground, background, Ctrl+C/Z/D#
While a command runs, your shell is busy — it's a foreground job. Three control keys change that:
| Key | Signal | Effect |
|---|---|---|
Ctrl+C |
SIGINT | interrupt the foreground job (cancel it) |
Ctrl+Z |
SIGTSTP | suspend it — pauses and returns you to the prompt |
Ctrl+D |
EOF | end-of-input — "close stdin" (how you exit python3 REPL, cat, ssh…) |
Ctrl+\ |
SIGQUIT | like Ctrl+C but dumps core (rarely used) |
A suspended job isn't dead — it's frozen. Job control brings it back:
sleep 300 # runs in foreground; press Ctrl+Z to suspend
jobs # -> [1]+ Stopped sleep 300
fg %1 # bring job 1 back to foreground (it resumes where it paused)
bg %1 # resume it in the BACKGROUND instead
jobs # -> [1]+ Running sleep 300 &
kill %1 # or just kill the job& at the end of a command starts it in the background immediately: python train.py & → [1] 12345, prompt returns. jobs lists background/stopped jobs, fg/bg manage them — but they only work in the shell that started them; closing the terminal kills them (that's what nohup/tmux solve, below).
Three special variables worth memorising: $$ is the shell's own PID, $! is the PID of the last background job (sleep 300 & echo $! prints the number kill wants), and $? is the last exit code (Part 1.5).
6.6 Ports and "address already in use"#
A port is a numbered door (0–65535) a process listens on so other programs can reach it — your dev server on :8000, a database on :5432, an API on :4000. "localhost:8000" means "this machine, port 8000".
The classic error: Address already in use / EADDRINUSE when starting a server — something is already bound to that port.
lsof -i :8000 # what process is using port 8000? (macOS/Linux)
lsof -iTCP:8000 -sTCP:LISTEN # only listeners, clearer
ss -tlnp | grep 8000 # Linux modern equivalent (iproute2) — netstat is deprecated
netstat -tlnp 2>/dev/null | grep 8000 # older Linux alternative (needs sudo for -p on some systems)
fuser -k 8000/tcp # Linux only: kill whatever holds the port (nuclear option)Example output (illustrative — PIDs/commands differ):
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Python 12345 you 11u IPv4 ... TCP localhost:irdmi (LISTEN)The fix is usually: find the PID in the lsof output and kill <pid> (it was probably a dev server you forgot), or pick a different port. lsof = "list open files" — a port is just a special file the kernel tracks.
6.7 Long-running tasks: nohup and tmux#
Background jobs (&, jobs) die when the shell exits — close the laptop lid, SSH drops, terminal crashes, and your 6-hour fine-tune is gone. Two fixes:
-
nohup(no hangup):nohup python train.py > train.log 2>&1 &— ignores SIGHUP so it survives the terminal closing. Simple but crude: no way back in, output goes to a file. -
tmux(terminal multiplexer, current release 3.8): a persistent terminal inside your terminal. Detach and reattach; sessions survive disconnects.bash tmux new -s train # new session named 'train' # ... run your long command ... # Ctrl+B then D # detach — session keeps running tmux ls # list sessions tmux attach -t train # reattach tmux kill-session -t train # end itInstall:
brew install tmux/apt install tmux/ inside WSLsudo apt install tmux. (There is no official native Windows build; WSL is the recommended route.) Awareness level — you'll meet it on remote GPU boxes in later modules.
Also worth knowing: screen (the older multiplexer), disown (bash builtin — remove a job from the shell's job table so it isn't killed on exit), and systemd services on real servers. For this path, nohup … & covers "run it and walk away", tmux covers "I want to come back to it".
Part 7: Talking to the network#
Deep-dive
Everything an AI engineer does with an LLM provider is network I/O. These are the tools for looking before you code.
7.1 ping, dig, nslookup — is the host even there?#
ping -c 4 example.com # send 4 ICMP echo requests (Linux/macOS; Windows: 'ping -n 4')
ping -c 1 api.openai.com # does the provider's host respond?
dig example.com # DNS: translate name -> IP (dig = "domain information groper")
dig +short example.com # just the IP(s)
nslookup example.com # older/simpler DNS lookup (present everywhere)
host example.com # simplest: name -> IPExample output (illustrative — timings and IPs differ per network):
PING example.com (93.184.216.34): 56 data bytes
64 bytes from 93.184.216.34: icmp_seq=0 ttl=56 time=12.345 ms
...
4 packets transmitted, 4 packets received, 0.0% packet losspingtests reachability and latency — "can I even get packets to this host?" Timeouts or 100% loss = firewall, DNS, or the host is down.dig/nslookuptest DNS — "what IP does this name resolve to?" A DNS failure looks likeping: cannot resolve example.com. Availability varies: all three ship on macOS and most full Linux installs; on minimal containers/imagesdig/host/nslookupmay be missing (bind-tools/dnsutilspackages) —nslookupis the most likely to exist everywhere.- These diagnose the network layer. If ping works but an API call fails, the problem is higher up (TLS, auth, the app) — that's 00.6 and 03.8.
7.2 curl — the HTTP swiss-army knife#
curl (Client for URLs) is how you call any HTTP API by hand — and it's the preview of exactly what 03.1 Part 1 does with an LLM provider. Master the flags:
| Flag | Effect |
|---|---|
-s / --silent |
no progress meter (clean output for piping) |
-S |
with -s, still show errors |
-i |
include response headers in output |
-I / --head |
HEAD request: headers only, no body |
-X METHOD |
HTTP method: GET (default), POST, PUT, DELETE… |
-H 'Name: value' |
add a request header (repeatable) |
-d 'data' |
request body (implies POST); -d @file.json reads from file |
-o file |
write body to file instead of stdout |
-O |
write body to file named after the URL's last segment |
-w 'fmt' |
print custom stats after transfer: %{http_code}, %{time_total} |
--fail / -f |
fail (exit 22) on HTTP errors ≥400 — no body saved |
-L |
follow redirects |
-v |
verbose: full request/response trace to stderr — THE debugging flag |
--connect-timeout N / --max-time N |
timeouts in seconds — always set these in scripts |
-u user:pass |
HTTP basic auth |
-k |
insecure: skip TLS certificate verification — almost never right |
-F 'name=@file' |
multipart file upload |
-G |
turn -d data into query string (for GET) |
# GET with headers shown
curl -s -i https://api.example.com/v1/models
# POST JSON (note the quotes — the JSON must survive the shell)
curl -s -X POST https://api.example.com/v1/chat \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{"model": "gpt-6-luna", "messages": [{"role": "user", "content": "hi"}]}'
# same, but save body to file and show status + timing
curl -s -o resp.json -w 'HTTP %{http_code} in %{time_total}s\n' \
--max-time 30 https://api.example.com/v1/models
# follow a redirect, fail on 4xx/5xx, verbose trace for debugging
curl -sSL --fail -v https://example.com/api 2>&1 | head -40Example output (illustrative — real responses need a key and network):
HTTP/1.1 200 OK
Content-Type: application/json
{"data": [{"id": "gpt-6-luna", ...}]}Three habits that save hours:
- Quote the JSON body:
-d '{"a": 1}'— single quotes stop the shell eating the". Double quotes work too but you must escape inner quotes. For anything complex,-d @payload.jsonfrom a file. -ior-w '%{http_code}': the status code is part of the answer. A200with an error message in the body and a401with a JSON error look identical if you only print the body.--max-time: a hung connection without a timeout hangs forever. In scripts, always bound it.
On Windows PowerShell: curl in Windows PowerShell 5.1 is an alias for Invoke-WebRequest — a different command with different flags (Microsoft Learn). Write curl.exe to get the real curl (it ships with Windows 10 1803+). In PowerShell 7+ the alias is gone, so curl works — but curl.exe is the safe habit everywhere.
7.3 wget, ssh, scp, dig#
wget: download files —wget https://example.com/file.tar.gz,wget -rrecursive mirror.curlcan do downloads too (-O);wgetis the classic "get this file" tool. (Not installed by default on macOS;brew install wgetif needed.)ssh(Secure Shell): remote shell on another machine —ssh user@host, then you're in their terminal. Keys are covered in 00.4.ssh -L 8080:localhost:80 hosttunnels a port (port forwarding — how you reach a remote dev server's localhost).scp(secure copy):scp file.txt user@host:~/— copy files over SSH.rsyncis the better tool for syncing directories (rsync -avz src/ user@host:dst/).dig/nslookup/host: DNS lookups — covered in 7.1.
These are awareness level for now: you'll use curl daily, ssh/scp when deploying (11C.1), wget occasionally.
Part 8: Shell scripting#
Deep-dive
When you catch yourself typing the same five commands twice, that's a script. A shell script is a file of commands the shell runs top to bottom — bash's own programming language.
8.1 Your first script#
#!/bin/bash
# hello.sh — the smallest useful script
set -euo pipefail
echo "Hello, ${1:-world}!" # ${1:-world}: arg 1, or 'world' if absentchmod +x hello.sh
./hello.sh # -> Hello, world!
./hello.sh ada # -> Hello, ada!
bash hello.sh grace # -> Hello, grace! (works without +x)8.2 Variables and quoting (the rules that matter)#
NAME=world
echo "Hello, $NAME" # double quotes: expands -> Hello, world
echo 'Hello, $NAME' # single quotes: literal -> Hello, $NAME
echo "Date: $(date +%F)" # command substitution inside double quotes
DIR="my project"
cd "$DIR" # MUST quote — unquoted splits on the space
cat "$DIR/file name.txt" # sameThe golden rules:
- Always quote variables:
"$VAR","${VAR}","$VAR/suffix". Unquoted$VARundergoes word splitting (spaces become separate arguments) and globbing (*expands) — the source of half of all shell bugs. - Single quotes are literal, double quotes expand
$VARand$(...). ${VAR:-default}and${VAR:?msg}for safe defaults and required args.
Two more tools for the same job: here-documents (cat > file <<'EOF' … EOF) feed multiple lines to a command until a lone EOF — you've used them to create app.log and friends; the 'EOF' quotes stop $ expansion inside. And prefer printf over echo for anything with escapes or flags — echo -n/echo -e behave differently across shells, while printf 'a\nb\n' is predictable everywhere.
8.3 Conditionals, loops, functions#
#!/bin/bash
# summarize_errors.sh — count and list ERROR lines from a log file.
# Usage: bash summarize_errors.sh <logfile> [level-to-count ...]
set -euo pipefail
LOG_FILE="${1:?usage: summarize_errors.sh <logfile> [level ...]}"
shift || true
LEVELS=("$@")
if [ ${#LEVELS[@]} -eq 0 ]; then
LEVELS=("ERROR" "WARN")
fi
count_matches() {
# $1 = level; prints the number of matching lines
grep -c "$1" "$LOG_FILE" || true
}
for level in "${LEVELS[@]}"; do
n=$(count_matches "$level")
if [ "$n" -gt 0 ]; then
echo "$level: $n"
fi
done
total=$(grep -cE 'ERROR|WARN' "$LOG_FILE" || true)
echo "total flagged: $total"Run it (this is the real script from the exercises):
Output:
$ bash summarize_errors.sh app.log
ERROR: 3
WARN: 1
total flagged: 4
$ bash summarize_errors.sh app.log ERROR INFO
ERROR: 3
INFO: 5
total flagged: 4
$ bash summarize_errors.sh
summarize_errors.sh: line 6: 1: usage: summarize_errors.sh <logfile> [level ...]
exit=1The pieces:
if [ cond ]; then … fi:[ ... ]is thetestcommand —[ "$n" -gt 0 ]is numeric greater-than,[ -f file ]file exists,[ -z "$s" ]empty string,[ "$a" = "$b" ]string equality. ([[ ... ]]is the bash/zsh extended form — prefer it in bash scripts.)for x in list; do … done: iterate.for f in *.txtloops over glob matches;for i in {1..10}counts.while read: the line-by-line loop —while read line; do … done < file(orcat file | while read line).- Functions:
name() { …; }—count_matchesabove takes$1inside. Declare helper variables withlocalso they don't leak into the rest of the script — without it every variable is global. Declare and assign on separate lines (local nthenn=$(...)):local n=$(cmd)reports the exit status oflocal, not ofcmd, soset -ewould never notice thatcmdfailed. - Arrays (bash/zsh):
LEVELS=("$@")collects all args;${#LEVELS[@]}is the count;"${LEVELS[@]}"expands each element quoted.
8.4 set -euo pipefail and arguments — the safety trio#
Put set -euo pipefail near the top of every script — after the shebang (and any leading comments), before the first command that can fail. Each flag fixes a classic silent-failure mode:
| Flag | Does | Catches |
|---|---|---|
-e (errexit) |
exit immediately if any command fails | a failed mkdir/curl doesn't let the script carry on and corrupt state |
-u (nounset) |
error on expanding an unset variable | $API_KEY typos become loud errors instead of empty strings |
-o pipefail |
a pipeline fails if any stage fails, not just the last | grep x file | head reports grep's failure, not head's success |
set -e is a safety net with holes, not a guarantee: bash deliberately ignores a failure inside a condition (if cmd; then, while cmd), on the left of &&/||, and inside a function called from such a place. So cmd || true (as summarize_errors.sh uses for grep -c, which exits 1 when it counts zero matches) is the explicit way to say "this command may fail, carry on", and anything that truly must succeed deserves its own if ! cmd; then echo 'cmd failed' >&2; exit 1; fi.
Arguments: $0 script name, $1 $2… positional args, $@ all args, $# count, "$@" all args quoted (each as one word — always use the quotes), shift drops $1.
${1:?msg} is the idiom for "required argument": prints msg and exits if $1 is unset — that's the usage error you saw.
When a script misbehaves, bash -x script.sh (or set -x inside it) traces every command before running it — the first debugging tool to reach for.
8.5 When to move to Python#
Shell is right for: gluing commands together, file shuffling, quick automation, deployment one-liners. Move to Python (01A onwards) when you need:
- real data structures (dicts, lists of objects) — shell "arrays" are painful
- JSON/XML/API parsing —
jq/sed/awkhit their limit fast - error handling you can reason about —
try/exceptbeatsset -eguesswork - anything over ~50 lines, anything others will maintain, anything with tests
The honest rule: prototype the pipeline in shell, rewrite the valuable part in Python. The shell skills aren't wasted — you still use the terminal to run the Python.
8.6 Aliases and task runners#
alias ll='ls -la' # ll now means ls -la (this shell only)
alias gs='git status' # shorten frequent commands
alias # list all aliases
unalias ll # remove one
type ll # what does ll resolve to? (alias/function/builtin/file)Aliases are per-shell-session unless saved in your dotfile — put the ones you want permanent in ~/.zshrc/~/.bashrc (then source the file to load them).
ShellCheck (shellcheck script.sh) is the standard linter for shell scripts — it catches the quoting bugs and portability traps this lesson warns about before they bite. Install: brew install shellcheck / apt install shellcheck / winget install koalaman.shellcheck. Run it on every script you write; treat its warnings as review comments.
Task runners: when a project has "the commands you always run" (uv run pytest, docker compose up), tools like make (a Makefile of named targets), just, or task give them names — make test instead of remembering the full command. Awareness only; 11C.1 and CI (11C.2) use them heavily. A Makefile is just a text file — you could write one in Module 00's stretch projects.
Part 9: Speed and safety#
Reference
9.1 Keyboard shortcuts that pay for themselves#
| Keys | Action |
|---|---|
Ctrl+A / Ctrl+E |
jump to start / end of the line (readline, bash/zsh; macOS also Cmd+←/→) |
Ctrl+R |
reverse history search — type a few letters, Enter to run, Esc to edit first |
Ctrl+U / Ctrl+K |
delete from cursor to start / end of line |
Ctrl+W |
delete previous word |
Ctrl+Y |
yank (paste) what Ctrl+U/K/W deleted |
Ctrl+L |
clear screen (= clear) |
reset |
restore the terminal after binary/TUI garbage (stty sane is the lower-level fix) |
Ctrl+C / Ctrl+Z / Ctrl+D |
interrupt / suspend / EOF (Part 6.5) |
↑ / ↓ |
previous / next history entry |
!! |
repeat last command; !grep last command starting with grep; !$ last command's last argument |
Tab / Tab Tab |
complete / list completions |
Ctrl+Shift+T or Cmd+T |
new terminal tab (varies by terminal app) |
| mouse: select text | copy (in most terminal apps); right-click or Cmd+V pastes |
The two that change your life: Ctrl+R (never retype a long command) and Tab completion (never typo a path). Everything else is gravy.
9.2 man, --help and tldr: reading documentation#
Three levels of documentation, cheapest first:
ls --help # quick usage — BUT not on macOS's BSD tools! see below
man ls # the full manual page (q to quit)
man -k keyword # search man pages for a keyword
man bash # the whole shell language reference
whatis ls # one-line summary
apropos network # search all man page descriptionsOutput (macOS, BSD userland — verbatim capture, November 2026):
$ ls --help
ls: unrecognized option `--help'
usage: ls [-@ABCFGHILOPRSTUWXabcdefghiklmnopqrstuvwxy1%,] [--color=when] [-D format] [file ...]
$ sed --version
sed: illegal option -- -
usage: sed script [-EHalnru] [-i extension] [file ...]
$ find --version
find: illegal option -- -
usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
$ sort --version
2.3-Apple (201)
$ awk --version
awk version 20200816
$ head --version
head: unrecognized option `--version'
usage: head [-n lines | -c bytes] [file ...]
$ xargs --version
xargs: unrecognized option `--version'
usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]
$ tr --version
tr: illegal option -- -
usage: tr [-Ccsu] string1 string2
$ cut --version
cut: illegal option -- -
usage: cut -b list [-n] [file ...]
$ wc --version
wc: illegal option -- -
usage: wc [-Lclmw] [file ...]
$ du --version
du: unrecognized option `--version'
usage: du [--libxo] [-Aclnx] [-H | -L | -P] [-g | -h | -k | -m]
$ df --version
df: unrecognized option `--version'
usage: df [--libxo] [-b | -g | -H | -h | -k | -m | -P] [-acIilnY] [-,] [-T type] [-t type]
$ which --version
which: illegal option -- -
usage: which [-as] program ...
$ file --version
file-5.41
magic file from /usr/share/file/magic
$ grep --version
grep (BSD grep, GNU compatible) 2.6.0-FreeBSDOn Linux (GNU coreutils) all of these work and print version/help. So the portable habit is: man <cmd> is the reliable documentation everywhere; --help works on Linux and PowerShell (Get-Help) but often not on macOS. The usage: line that BSD tools print on a bad flag is itself a compact help — read it.
tldr (too long; didn't read) gives practical examples per command — community-maintained pages at tldr.sh / github.com/tldr-pages. The brew install tldr formula is deprecated (unmaintained C client); the current official clients are tlrc (Rust — brew install tlrc, winget install tldr-pages.tlrc) or the Python client via pipx install tldr. Then tldr tar, tldr curl, tldr find show copy-pasteable examples — the fastest way to remember flags.
Reading a man page: sections are NAME (one line), SYNOPSIS (syntax), DESCRIPTION, then flags. You mostly need NAME + SYNOPSIS + the flag you're using. man ls | col -b | less strips formatting if it looks ugly.
9.3 Terminal safety#
The terminal is powerful — that's the point and the risk. Rules that keep you out of trouble:
- Never paste a command you don't understand, especially one-liners from the internet, AI chatbots, or Stack Overflow.
curl … | shdownloads and immediately executes a script — if the URL or the script is hostile or just wrong, it runs with your privileges. The safe pattern:curl -O urlto download, read the file, then run it. Theuvinstaller (curl -LsSf https://astral.sh/uv/install.sh | sh) is a legitimate use — it's from the official docs (03.1 §4.1) — but the habit of reading before piping to sh is what makes it safe to judge each case. rm -rf,chmod -R,git push --force,dd,mkfs: destructive or hard-to-reverse. Rehearse in a scratch dir first, double-check paths, prefer-i/--interactiveor dry-run flags where they exist.- Secrets in the terminal:
export API_KEY=sk-…puts the key in your shell history (history,~/.zsh_history) — visible to anyone with file access and synced by dotfile managers. Better: put it in.env(loaded by tools, never echoed) or useread -sto type it without echo. Neverecho $API_KEYto "check it" — the key lands in your terminal scrollback, and from there in any screenshot, screen-share or pasted log. Check it's set with[ -n "$API_KEY" ] && echo setinstead. sudo: covered in 6.2 — least privilege, understand before you run.>overwrites silently:cmd > filedestroysfile's contents with no warning.>>appends. When unsure,ls -l filefirst or use a new filename.- Trust your eyes over your fingers: the terminal has no undo. Slow down on destructive commands; speed up on everything else.
The cheat sheet#
Every common task → macOS/Linux/WSL → Windows PowerShell. (In WSL, use the left column verbatim.)
| Task | macOS / Linux / WSL | Windows PowerShell |
|---|---|---|
| Where am I? | pwd |
Get-Location (pwd alias) |
| List files | ls -la |
Get-ChildItem -Force (ls alias) or dir |
| Change dir | cd path |
cd path / Set-Location path |
| Make dir | mkdir -p a/b |
mkdir a\b (or New-Item -ItemType Directory) |
| Copy | cp -r src dst |
Copy-Item -Recurse src dst |
| Move/rename | mv a b |
Move-Item a b |
| Delete | rm file / rm -r dir |
Remove-Item file / Remove-Item -Recurse dir |
| View file | cat file / less file |
Get-Content file / more.com file |
| First/last lines | head -n 5 / tail -n 5 |
Get-Content file -TotalCount 5 / -Tail 5 |
| Follow a log | tail -f app.log |
Get-Content app.log -Wait -Tail 20 |
| Search text | grep -rn pat dir/ |
Get-ChildItem dir -Recurse -File | Select-String -Pattern pat (or rg) |
| Find files | find . -name '*.py' |
Get-ChildItem -Recurse -Filter *.py |
| Count lines/words | wc -l file |
(Get-Content file | Measure-Object -Line).Lines |
| Sort/unique | sort file | uniq -c |
Get-Content file | Sort-Object | Group-Object |
| JSON query | jq '.field' f.json |
jq '.field' f.json (install jq) or ConvertFrom-Json |
| Env var set | export X=1 |
$env:X = "1" |
| Env var read | echo $X |
echo $env:X |
| List env | env / printenv |
Get-ChildItem Env: |
| Which program | command -v x |
Get-Command x |
| Search history | Ctrl+R / history |
Ctrl+R (PSReadLine) / (Get-PSReadlineOption).HistorySavePath |
| Process list | ps aux / top / htop |
Get-Process |
| Kill process | kill PID / kill -9 PID |
Stop-Process -Id PID / -Force |
| Network check | ping host, curl -sI url |
Test-Connection host, curl.exe -sI url |
| DNS lookup | dig host / nslookup host / host host |
Resolve-DnsName host / nslookup host |
| What's on a port? | lsof -i :8000 / ss -tlnp |
Get-NetTCPConnection -LocalPort 8000 |
| Download file | curl -O url / wget url |
curl.exe -O url / Invoke-WebRequest url -OutFile f |
| Disk space | df -h |
Get-PSDrive |
| Compare files | diff a b / diff -u a b |
Compare-Object (Get-Content a) (Get-Content b) |
| Bundle/extract | tar -czf a.tgz dir / tar -xzf a.tgz |
Compress-Archive / Expand-Archive |
| Copy to clipboard | pbcopy / xclip / wl-copy |
Set-Clipboard / clip |
| Permissions | chmod 755 f, ls -l |
icacls / (Get-Acl f) (different model — see 6.2) |
| Run script | bash script.sh / ./script.sh |
.\script.ps1 (after Set-ExecutionPolicy) or powershell -File script.ps1 |
Decision table: which tool when#
| You want to… | Use | Not |
|---|---|---|
| Look at a file quickly | cat (all), less (big), head/tail (ends) |
opening an editor |
| Search file contents | grep/rg |
find (that's for names) |
| Find files by name/type | find |
grep |
| Count/shape text | wc, sort|uniq, cut, awk |
writing a script for one-offs |
| Parse JSON | jq |
grep on JSON (breaks on nested quotes) |
| Edit many files' text | sed (simple), Python (complex) |
manual edits |
| Repeat a command pattern | shell loop → script → Python | retyping |
| Run something long | nohup … & or tmux |
bare & (dies with terminal) |
| Free a stuck port | lsof -i :PORT then kill PID |
rebooting |
| Debug a failing command | echo $?, cmd 2>&1 | head, -v flag |
guessing |
Failure gallery#
The errors you'll actually meet, and what they mean:
| Symptom | Usually means | First check |
|---|---|---|
command not found (exit 127) |
typo, or not installed, or not on PATH | command -v name |
Permission denied (126) |
no execute bit, or file/dir perms block you | ls -l file; chmod +x |
No such file or directory |
path wrong, wrong directory, or glob matched nothing | pwd, ls, quote the name |
is a directory |
you ran cat/grep on a folder |
add -r for grep, or pick a file |
ambiguous redirect (bash) / no such file or directory: (zsh) on > |
target directory doesn't exist | ls the parent dir |
Argument list too long |
glob expanded to thousands of files | xargs or find -exec |
curl: (6) Could not resolve host |
DNS/network down | ping, dig |
curl: (7) Failed to connect |
host reachable but port closed/filtered | curl -v, check port |
curl: (28) Connection timed out |
--max-time hit or network stall |
increase timeout, check network |
HTTP 401/403 from API |
bad/missing key | check env var is exported, not just set |
HTTP 429 |
rate limited | backoff (01B.9, 03.8) |
Address already in use |
port taken | lsof -i :PORT |
sed: 1: "file.txt … invalid command code f on macOS (the wording varies with your file name) |
BSD sed -i takes the next word as a backup suffix, so it read your script as the suffix and your file name as the script |
add '' after -i |
zsh: no matches found: *.xyz |
glob matched nothing (zsh errors where bash passes through) | quote the pattern or check dir |
bash: $VAR: unbound variable |
set -u caught a typo/unset var |
echo ${VAR:-default} to default it |
| script runs on Mac, fails on Linux | BSD vs GNU tool difference (sed -i, date, stat) |
check --version/man page |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The terminal and the shell are the same thing." | The terminal emulator is the window/keyboard; the shell is the program inside it that reads commands. You can swap either independently. |
"$? holds the exit code of the last command I ran a while ago." |
It's overwritten by every command — check it immediately, before the next one. |
| "A non-zero exit code always means the program crashed." | It means "not success" — could be a handled error (grep found no match → 1), bad usage (→ 2), or a kill signal (128+n). Read the message too. |
"rm moves files to a trash I can restore." |
On macOS/Linux rm is permanent. Use mv to a scratch dir or a trash tool if you want undo. |
| "Hidden files are secret/protected." | The dot is only a listing convention — cat .env reads it fine. Secrets need file permissions and .gitignore, not just a dot. |
| "macOS and Linux run the same commands, so they'll behave identically." | macOS ships BSD userland: sed -i needs '', --help/--version often missing, stat/date flags differ. Same names, different flags. |
"export is required for a variable to exist." |
X=1 creates a shell variable immediately; export only marks it for inheritance by child programs. |
"Setting a variable in .env exports it to the shell." |
.env is just a text file — tools like python-dotenv/uv --env-file load it into the process environment. The shell never reads it automatically. |
"command not found means it's not installed." |
It might be installed but its directory isn't on PATH — command -v distinguishes. |
| "Pipes run commands one after another." | They run concurrently — data flows through as it's produced. That's why yes | head -1 terminates. |
"> and >> differ only in speed." |
> truncates (destroys) the file; >> appends. > on the wrong file loses data with no warning. |
| "Ctrl+Z killed my program." | It suspended it — fg/bg/jobs resume it. Ctrl+C (SIGINT) is the cancel. |
"kill -9 is the way to stop a process." |
SIGKILL skips all cleanup — corrupt files, half-written DBs. SIGTERM (plain kill) first; -9 only if it ignores TERM. |
"A .sh file runs because it has a shebang." |
The shebang picks the interpreter, but you still need the execute bit (chmod +x) to run ./script.sh — or invoke it as bash script.sh. |
| "PowerShell is just bash with different commands." | It's a different object pipeline (Get-ChildItem returns objects, not text) — more powerful, not interchangeable. In WSL you get real bash anyway. |
| "Quoting is only about spaces." | Quotes also control variable expansion ("$x" expands, '$x' doesn't) and word splitting/globbing — the source of most shell bugs. |
"I can curl … | sh because it's from the official site." |
It executes whatever the server returns right now, as you, with no review. Download, read, then run — every time. |
"sudo makes a command safer." |
It makes it more dangerous — root bypasses all permission checks. It's for when permissions genuinely block you, not a fix for confusion. |
Key takeaways#
- Terminal emulator ≠ shell ≠ command. The window draws text, the shell reads commands and launches programs, the command does the work.
- A command = program + flags + arguments. Flags modify behaviour (
-l,--recursive), arguments are targets.--separates them when names start with-. - Exit code 0 = success; anything else = failure.
$?holds it, overwritten by every command.&&/||/;chain on it. - stdin/stdout/stderr are three channels; pipes connect stdout→stdin, redirection connects them to files/
/dev/null.2>&1order matters. - Paths: absolute from
/(orC:\), relative frompwd.~home,.here,..parent. Quote names with spaces. - The toolbox:
grepcontents,findnames,sort|uniqshape,cut/tr/sed/awktransform,jqparses JSON,diffcompares files,tarbundles them, pipes chain them all. - Variables: shell vars are private,
exported env vars reach child programs.PATHis the colon-separated search path;command -vfinds programs. Dotfiles configure startup;.envis for app secrets. - Permissions:
rwxper owner/group/other;chmod 755scripts,644data,600secrets. Execute bit + shebang = runnable script. - Processes/jobs:
ps/topinspect,killsignals (TERM polite, KILL last resort), Ctrl+C/Z/D control,&/jobs/fg/bgmanage,lsof -i :portfrees ports,nohup/tmuxsurvive disconnects. - Network:
ping/digdiagnose connectivity/DNS,curlis the HTTP workhorse — quote JSON, set--max-time, check%{http_code}. - Scripts: shebang +
set -euo pipefail+ quoted"$@"args. Know when to graduate to Python. - Safety: no undo in the terminal — rehearse destructive commands in scratch, read before
curl|sh, never echo secrets,sudosparingly. - BSD vs GNU: macOS tools differ from Linux —
manis the portable documentation,--help/--versionoften aren't there.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Terminal emulator | The window/keyboard app that draws text and forwards keystrokes to a shell |
| Shell | The program that reads commands and launches other programs (zsh, bash, fish, PowerShell) |
| Command | A program the shell runs, plus its flags and arguments |
| Prompt | The text the shell prints when ready for input ($ , custom formats) |
| Working directory | The directory the shell is currently in; relative paths resolve against it |
| Absolute / relative path | Path from the root (/…, C:\…) vs from the working directory |
~, ., .. |
Home directory; this directory; parent directory |
| Hidden file | A file whose name starts with . (Unix) — hidden from plain ls |
| Glob / globbing | Wildcard expansion of *, ?, […], {a,b} into filenames |
| Quoting | "…" (expands vars) vs '…' (literal) vs \ escapes — controls splitting/expansion |
Pipe | |
Connects one command's stdout to another's stdin |
| Redirection | >, >>, <, 2>, 2>&1, /dev/null — route streams to files or nowhere |
| stdin / stdout / stderr | The three standard channels: input (0), output (1), errors (2) |
Exit code / $? |
The numeric success/failure result a command returns; $? holds the last one |
| Shell variable vs environment variable | Private to the shell vs inherited by child programs (export) |
PATH |
Colon-separated list of directories searched for commands |
| Dotfile | A hidden .-prefixed config file (.zshrc, .env, .gitignore) |
| Login vs interactive shell | Shell started at login (reads .zprofile/.bash_profile) vs nested (reads .zshrc/.bashrc) |
Permission bits (rwx) |
Read/write/execute flags per owner/group/other; chmod sets them |
Ownership / sudo |
File owner+group; sudo runs a command as root |
Shebang #! |
First-line #!/path/to/interpreter telling the kernel what runs a script |
| Process / PID | A running program and its numeric ID |
| Signal | A numbered message to a process (SIGINT=2, SIGTERM=15, SIGKILL=9 everywhere; job-control numbers differ by OS — kill -l lists yours) |
| Job / foreground / background | A shell-managed command; foreground blocks the prompt, background (&) doesn't |
| Port | A numbered endpoint (0–65535) a process listens on for connections |
lsof |
Lists open files/ports — lsof -i :8000 finds what holds a port |
nohup / tmux |
Ignore-HUP wrapper / terminal multiplexer for surviving disconnects |
curl |
Command-line HTTP client |
jq |
Command-line JSON processor |
sed / awk |
Stream editor / columnar text-processing language |
xargs |
Builds command lines from stdin |
diff |
Line-by-line file comparison; -u gives unified (patch-style) output, exit 1 on differences |
tar |
Archive tool: -czf creates a gzipped tarball, -xzf extracts, -tzf lists |
cron / launchd / Task Scheduler |
Per-OS schedulers that run commands on a timetable |
| Clipboard tools | pbcopy/pbpaste (macOS), xclip/wl-copy (Linux), clip/Set-Clipboard (Windows) — pipe text to/from the clipboard |
| Command substitution | $(cmd) — inserts a command's output as text |
| Shell alias | A shell shortcut name for a longer command, defined with alias in a dotfile |
Locale (LC_ALL, LC_COLLATE) |
Environment settings that control sort order, character classes and message language; LC_ALL=C gives plain byte order |
| Here-document | <<'EOF' — feed the following lines to a command until a lone EOF |
set -euo pipefail |
Script safety flags: exit-on-error, nounset, pipefail |
| BSD vs GNU userland | macOS's BSD-derived tools vs Linux's GNU tools — same names, different flags |
man page |
The system manual for a command |
tldr |
Community cheat-sheet pages with command examples |
All terms are also collected in the glossary.
Exercises#
Use the same scratch folder and demo files from Part 2 — if you still have it, cd back there; otherwise recreate it with the block at the start of Part 2. The exercises use the same app.log (9 lines), words.txt, people.csv and tickets.json as the lesson body — the solutions' line numbers and counts come from those files, not smaller copies.
- Navigation:
projects/ai-path/notesalready exists from the demo data — add two files to it, then use onlycd,pwd,lsto prove you're insidenotes. Which single command takes you back toprojects? - Hidden files: the demo data already has
.envand.hidden-plan. Show thatlshides them butls -ashows them, and thatcat .envstill works (it's an empty file — exit 0). - Quoting and globs:
mkdir -p "my dir" && touch "my dir/a file.txt". Getlsto list the contents ofmy dir, show the error when you forget quotes, then write onelscommand listing only top-level.txtfiles and one matchingwords.txtandapp.logbut notpeople.csv. - Files: append one more line to
app.logwith>>(printf '2026-11-01T09:00:14Z DEBUG cache hit\n' >> app.log), then prove withwc -lthat it went from 9 to 10 lines. Copypeople.csvtopeople-backup.csvwithcp, then rename the backup withmv. - Reading and pipes: use
head -2andtail -2onapp.logto show the first and last two lines. Thencat app.log | grep -c ERRORandgrep -c ERROR app.log— same answer? Why reach for the pipe form? - Redirection: run
grep ERROR app.log > errs.txt, thenwc -l errs.txt. Now runls /nope 2>/dev/null; echo "exit=$?"and explain why the error text didn't appear but the exit code did. - grep: find all lines containing
dbwith line numbers (grep -n db app.log). Then invert it: all lines that do not containERROR. - sort/uniq/cut:
sort words.txt | uniq -c— what does each column mean? Thencut -d, -f1 people.csv. - jq: from
tickets.json, extract.request_id, the number of tickets, and only thesubjectof tickets whosestatusis"open". Usejq -rfor unquoted output. - Variables and PATH:
export TESTVAR=hello, then in a child shell (sh -c 'echo $TESTVAR') show it's visible;unset TESTVARand show it's gone. ExplainTESTVAR=hivsexport TESTVAR=hi. Thencommand -v python3andcommand -v ls— what do they print and why? Finish withecho $PATH | tr ':' '\n' | head -3. - Permissions: create
script.shwith#!/bin/bashandecho hi. Show./script.shfails with exit 126, thenchmod 755 script.shmakes it work. Explain the two requirements. - Signals/jobs: start
sleep 60 &, note its job number withjobs, thenkill %1. What signal didkillsend by default? - Script: adapt
summarize_errors.shto also print the total line count of the log file (wc -l "$LOG_FILE"). Run it onapp.log. - Safety: in your scratch dir, rehearse the safe-delete habit: create
a/ b/ c/with files, then delete onlya/usingrm -r a— and explain whyrm -rf a b ctyped from the wrong directory would be catastrophic. - curl (read-only): write the
curlcommand you would run to GEThttps://api.example.com/v1/modelswith a 10-second timeout and HTTP status shown — but don't run it (no network in this phase). Explain each flag. - Compare and package (3.8): create two three-line files that differ in exactly one line, show the difference with
diff -u, and checkecho $?straight afterwards. Then bundle the folderprojects/intoprojects.tar.gz, list its contents without extracting, and extract it into a new empty folderrestore/. Prove the copy matches withdiff -r projects restore/projects.
Solutions (worked — commands and real outputs where deterministic)
cd projects/ai-path/notes && touch a.txt b.txt && pwd && ls→pwdprints the absolute path;lsshowsa.txt b.txt ideas.md todo.txt.cd ../..returns toprojects(notes→ai-path→projects).ls→ no dotfiles;ls -a→.,..,.env,.hidden-planplus the rest;cat .env→ empty output, exit 0.ls "my dir"→a file.txt;ls my dir→ls: my: No such file or directory+ls: dir: No such file or directory.ls *.txt→ top-level.txts only (case.txt,counts.txt,empty.txt,five-lines.txt,greek.txt,greeting.txt,no-newline.txt,nums.txt,words.txt— plus any you added);ls {words.txt,app.log}orls words.txt app.logfor the pair.printf '…\n' >> app.log && wc -l app.log→10 app.log(was 9).cp people.csv people-backup.csv && mv people-backup.csv people2.csv—people.csvitself is untouched.head -2 app.log→ first two lines;tail -2→ last two (which now include your appended DEBUG line).cat app.log | grep -c ERROR=grep -c ERROR app.log=3. The pipe is redundant for a single query — prefer it when data is already flowing through a pipeline.wc -l errs.txt→3 errs.txt.ls /nope 2>/dev/nullsends stderr to the void;echo "exit=$?"→exit=1on macOS (2with GNUlson Linux/WSL, see 1.5) — the error text was discarded but the exit code survived (it's a number, not text).grep -n db app.log→3:…db connection…and6:…db connection…(lines 3 and 6 of the 9-line log);grep -v ERROR app.log→ the 6 non-ERROR lines (7 after exercise 4's append).uniq -ccolumns: count then value (3 apple= "apple" appears 3×).cut -d, -f1→name,ada,alan,grace,linus,margaret.jq '.request_id'→"req-1042";jq '.tickets | length'→4;jq -r '.tickets[] | select(.status=="open") | .subject'→Printer broken,Login loop,Dark mode.export TESTVAR=hello && sh -c 'echo $TESTVAR'→hello; without export the child sees nothing — that's the shell-variable vs environment-variable difference.command -v python3→ e.g./opt/homebrew/bin/python3;command -v ls→/bin/ls. PATH is the ordered search path — first match wins../script.sh→Permission denied,exit=126; afterchmod 755→hi. Needs both the execute bit and a shebang naming the interpreter.[1] 12345(PID varies);kill %1sends SIGTERM (15 on every OS) — the polite default.- Add
echo "lines: $(wc -l < "$LOG_FILE")"— useswc -l < file(stdin redirect) so output is just the number. On the appended log it prints10(macOS's BSDwcpads the number with leading spaces, which is harmless here). mkdir a b c && touch a/f b/f c/f && rm -r aremoves onlya.rm -rf a b cfrom the wrong cwd (say$HOME) would delete reala/b/cdirs — no undo.curl -s -o models.json -w 'HTTP %{http_code} in %{time_total}s\n' --max-time 10 https://api.example.com/v1/models—-ssilent,-osave body,-wprint status+timing,--max-timetimeout.printf 'a\nb\nc\n' > x.txt; printf 'a\nB\nc\n' > y.txt; diff -u x.txt y.txt; echo $?prints the@@hunk and then1(differences found;0would mean identical). Thentar -czf projects.tar.gz projects(creates),tar -tzf projects.tar.gz(lists, no extraction),mkdir restore && tar -xzf projects.tar.gz -C restore(extracts), anddiff -r projects restore/projectsprints nothing and exits0when the trees match. Here the archive stores paths with aprojects/prefix, which is why the comparison target isrestore/projects.
Where you'll use this in the AI path#
The terminal is the substrate every later module stands on:
- 03.1 — First API calls: the whole "an LLM call is an HTTP request" part is
curlwith headers and JSON bodies — exactly the flags from 7.2. Its secrets section (§3.4) isexport,.envandos.environfrom Part 5. - 03.1 §4.1:
uvcommands,uv run, project setup — all run in a working directory (1.7) with PATH correctly set (5.3). - 11A.1 — Tracing and observability: LLM traces stored as JSONL "queryable with
jq" — your 4.8 skills applied to real trace data; its viewer is a CLI you run in the terminal. - 11C.1 — Deployment: Dockerfiles,
docker build/run, uvicorn workers,lsof/ports,nohup/tmux/systemdfor long-running services — Parts 6–7 at production scale. - 11C.2 — CI/CD: shell steps in GitHub Actions/GitLab CI are the same commands;
make/task runners andset -euo pipefaildiscipline apply. - 00.3 — Git / 00.4 — GitHub:
git,gh,sshkeys — the very next lessons, all terminal work. - 00.9 — Working like an engineer: debugging is reading exit codes, stderr (
2>&1), and error messages — Part 1.5–1.6 and the failure gallery are its foundation.
Check yourself#
- Name the three pieces involved when you "open the terminal" and type
ls.Terminal emulator (the window), the shell (the command-reading program), and the command itself (ls). - What does the shell store in
$?, and what are exit codes 0, 1, 2, 126, 127 and 128+15 roughly?The last command's exit code.0=success,1=general failure,2=misuse/bad usage,126=found but can't execute (no +x),127=command not found,128+15=killed by SIGTERM (signal 15). - What's the difference between stdin, stdout and stderr, and why does
cmd | wc -lignore stderr?stdin=input channel, stdout=normal output, stderr=errors.cmd | wc -lpipes only stdout; stderr still goes to your screen, so it doesn't corrupt the count. - Two ways a correct-looking path fails: are
Notes.TXTandnotes.txtthe same file on a default Mac vs Linux — and why doesls my report.txtfail when the file exists?Same file on default Mac (APFS case-insensitive) and Windows (NTFS); different on Linux (ext4 case-sensitive) — code openingConfig.yamlworks locally, fails on a Linux server. And a space splitsmy report.txtinto two arguments — quote it:ls "my report.txt". sort words.txt | uniq -cprints3 apple. What do the two columns mean, and why doesuniqalone miss duplicates?Count of occurrences and the value.uniqonly removes adjacent duplicates, sosortmust run first to group them.- What's the difference between
>and>>, and between2>and2>&1?>truncates/overwrites;>>appends.2>sends stderr to a file;2>&1merges stderr into stdout's destination. export X=1vsX=1— which reaches a child Python process, and how doesos.environsee it?exportreaches the child (environment inheritance); plain assignment doesn't. Python sees it viaos.environ["X"]/os.environ.get("X").- Decode
-rwxr-x---: who can read, write and execute — and why ischmod 600right for~/.ssh/id_ed25519rather than644?Owner: rwx = read+write+execute. Group: r-x = read+execute (no write). Other: --- = nothing.600=rw- --- ---— a private key readable only by its owner;644would expose it to every user. ./script.shgives "Permission denied" (exit 126). List the two things required to run it directly.The execute bit (chmod +x) and a shebang (#!) naming the interpreter — or invoke viabash script.shwhich bypasses both.Ctrl+Zthenjobsshows[1]+ Stopped. How do you (a) resume it in the foreground, (b) kill it?(a)fgorfg %1. (b)kill %1(SIGTERM) orkill -9 %1.- A server says "address already in use" on port 8000. What's the first command to run and what does it tell you?
lsof -i :8000— shows which process/PID is listening; usually a forgotten dev server tokill. sed -i 's/a/b/' f.txtworks on your Linux box but fails on macOS. Why, and what's the fix?macOS's BSD sed requires a backup-extension argument to-i;sed -i '' 's/a/b/' f.txt(empty string = no backup). GNU sed takes-ibare.- What's wrong with
curl -s https://get.tool.io/install.sh | sh, and what's the safer pattern?It runs whatever the server returns as you, unreviewed — a hijacked/malformed script executes immediately. Safer:curl -O url, read the file, then run it. - When should a shell script become Python? Give three triggers.Needs real data structures, JSON/API parsing, complex error handling, >~50 lines, or others will maintain/test it.
set -euo pipefail— what does each flag catch?-eexits on first failed command;-uerrors on unset variables;-o pipefailfails a pipeline if any stage fails.
Further resources#
- Bash Reference Manual (GNU): the definitive shell reference —
set -euo pipefail, parameter expansion${VAR:-default}, all of it. - zsh documentation and fish documentation: if you use those shells.
- tldr pages / github.com/tldr-pages: community cheat-sheets per command.
- jq manual: the full filter language.
- curl tutorial and
man curl: every flag in depth. - Apple Terminal User Guide: macOS-specific shell behaviour.
- Microsoft Learn: PowerShell and curl on Windows: the Windows side.
- Explain Shell: paste a command, get a visual breakdown of every flag — great for learning.
- regexone: learn regular expressions interactively (they power
grep,sed,awk,jq'stest). - Julia Evans, Wizard Zines — Bite Size Command Line!, Bite Size Bash! and The Secret Rules of the Terminal: the friendliest terminal zines on the internet.
← 00.1 — Setting Up Your Computer for Development | Module 00 overview | 00.3 — Git Fundamentals →