Lesson 9 of 18Your tools
Shell Power Tools
Quoting, globbing, text pipelines, find and xargs, jq for JSON, exit codes and dotfiles: the shell skills you use every day at work.
It is 4pm and the API is slow. Your lead asks: "Is someone hammering us? Which IPs sent the most requests in the last hour?" There is no dashboard for that, only a 2 GB access log on a server. An engineer who knows the shell answers in thirty seconds with one line. An engineer who does not opens the file in an editor, which freezes. This lesson is the toolkit for the first engineer: the small programs and rules that turn the terminal from a place where you type cd into the fastest data tool you own.
You already know pipes, > and >>, and basic grep from The Terminal. Here you go further: how the shell reads your line before anything runs, the text tools that make pipelines useful, safe ways to act on many files, JSON on the command line, and making your setup your own.
Getting help without leaving the terminal
Every tool here has more options than you will ever memorize. Senior engineers do not memorize them either. They know how to look them up in ten seconds.
man grep # the full manual page (q to quit, /word to search, n for next match)grep --help # a shorter summary, on most GNU toolstldr tar # community cheat sheets with real examples (install it first)A man page starts with a synopsis written in a small grammar. [ ] means optional, ... means "one or more", and | means "one or the other":
grep [-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-e pattern] [file ...]So grep takes optional flags, then a pattern, then zero or more files. With no files, it reads from standard input, which is exactly why it works in the middle of a pipe.
A few keyboard shortcuts pay for themselves in a day. They work in both zsh and bash:
| Keys | Does |
|---|---|
| Ctrl+A / Ctrl+E | Jump to the start / end of the line |
| Ctrl+U | Delete everything before the cursor |
| Ctrl+W | Delete the previous word |
| Ctrl+R | Search history; press again for older matches |
!! | The whole previous command, as in sudo !! |
cd - | Go back to the previous directory |
How the shell reads your line
Before any program runs, the shell rewrites what you typed. Most confusing shell bugs come from not knowing this order. A program like rm never sees your quotes or your *. It receives a finished list of arguments.
rm "my notes.txt" old.txt becomes two words after the command: my notes.txt and old.txt. The double quotes kept the space inside one word.
Python's shlex module splits a line with the same rules as step 1, so you can see what a program would receive:
Press Run (⌘ Enter) to see what happens.The rules that follow from this:
- Single quotes are completely literal. Use them for patterns:
grep 'price: $5',awk '{print $1}',jq '.items[]'. - Double quotes still expand
$VARand$(...), but keep the result as one word. Put them around every variable:"$file". - Globs (
*any characters,?exactly one character,[abc]one of these) are matched against filenames by the shell. In zsh,**/*.pysearches every subfolder. In bash it needsshopt -s globstar, which only exists in bash 4 and later.
f="Q3 report.pdf", and the folder contains Q3, report.pdf and Q3 report.pdf. What does rm $f delete?The text toolkit
Logs, CSV exports, config files and command output are all lines of text. A handful of tools, each doing one job, cover nearly everything:
| Tool | Job | Example |
|---|---|---|
grep | Keep lines that match | grep -v DEBUG app.log (-v inverts) |
sort | Sort lines | sort -n numeric, -r reverse, -k2 by column 2 |
uniq -c | Count adjacent repeats | always after sort |
wc -l | Count lines | grep -c counts matches directly |
head / tail | First / last lines | tail -n 100, tail -f to follow |
cut | Pick columns by a delimiter | cut -d, -f2 users.csv |
tr | Translate or delete characters | tr 'a-z' 'A-Z', tr -d '\r' |
sed | Find and replace in a stream | sed 's/http:/https:/g' |
awk | Columns split on whitespace, plus logic | awk '$9 >= 500' |
less | Read a big file | /text search, G end, g start, q quit |
awk deserves one more sentence. It splits each line on whitespace into $1, $2 and so on ($0 is the whole line), runs your condition and action, and can keep totals: awk '{sum += $10} END {print sum}' adds up column 10. You can go years using only print $N and simple conditions.
Now the question from the start. In the common access log format, the client IP is the first field:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -n 10awk prints field 1 of every line, so 2 GB of log becomes a column of IP addresses.
The sort before uniq matters because uniq only compares each line with the one directly above it. Run this to see what goes wrong without it:
Press Run (⌘ Enter) to see what happens.What does the last line print? (Ignore leading spaces.)
printf 'b\na\nb\nc\nb\na\n' | sort | uniq -c | sort -rn | head -n 1
Two more everyday pipelines. Every TODO in the repo, with file and line, skipping dependencies:
grep -rn "TODO" --include='*.py' --exclude-dir=.venv .rg -n "TODO" # ripgrep: faster, and skips .gitignore'd files by defaultAnd a quick replace with sed, previewed first:
sed 's/http:/https:/g' config.yaml # print the result, change nothingsed -i.bak 's/http:/https:/g' config.yaml # edit in place, keep config.yaml.bakFinding files and acting on them
find walks a directory tree and filters by name, type, size or age. fd is a friendlier modern alternative that, like rg, respects .gitignore.
find . -name '*.py' -mtime -1 # .py files modified in the last 24 hoursfind . -type f -size +100M # files over 100 MBfind . -name '__pycache__' -type d # directories by namefd -e py # fd: every .py file, ignoring .gitignore'd onesQuote the pattern ('*.py') so find receives the star. Unquoted, the shell may expand it to the .py files in the current folder first, and find gets the wrong arguments.
To run a command on every file found, pipe into xargs, which turns lines of input into arguments. The safe form uses -print0 and -0, which separate names with a null byte instead of a newline or space:
find . -name '*.log' | xargs wc -l # breaks on "my app.log"find . -name '*.log' -print0 | xargs -0 wc -l # safe with any filenamefind . -name '__pycache__' -type d -prune -exec rm -rf {} + # find can run commands itselfThe null byte is the one character that cannot appear in a filename, so the split is always right. PowerShell avoids the problem completely because it passes file objects, not text.
JSON on the command line with jq
Every API returns JSON, and jq is the standard tool for it. It is preinstalled on recent macOS, available as apt install jq on Ubuntu, and winget install jqlang.jq on Windows. Given a response like {"items": [{"id": 1, "name": "Ada", "active": true}, ...]}:
jq '.items[] | .name' users.json # "Ada" "Linus" "Grace", one per linejq -r '.items[] | .name' users.json # -r: raw strings, no quotesjq '.items | length' users.json # 3jq -r '.items[] | select(.active) | .name' users.jsoncurl -s https://api.example.com/users | jq '.items[0]'A jq filter reads left to right: .items takes a field, [] streams each element of the array, and | passes each one to the next filter. Use -r whenever the output feeds another command, or you will be passing literal quote characters along.
Exit codes, chaining and redirects
Every command finishes with an exit code: 0 means success, anything else means failure. echo $? prints the last one. The shell's chaining operators read those codes:
mkdir build && cd build # cd runs only if mkdir succeededgrep -q "DEBUG=true" .env || echo "debug is off" # run the right side only on failuremake clean; make # ; runs the next command no matter whata && b || c is not a true if/else. If b itself fails, c runs too. For anything important, write a real if, which you will see in Shell Scripting.
npm test && git push || echo 'tests failed'. The tests pass but the push is rejected by the server. What happens?Programs have two output streams. stdout (stream 1) is the normal output, and stderr (stream 2) is for errors and progress. > redirects stdout only, which is why errors still appear on screen when you save output to a file.
pytest > results.txt 2>&1 # both streams into the file (order matters)pytest 2>&1 > results.txt # wrong: stderr still goes to the screenfind / -name nginx.conf 2>/dev/null # throw away "Permission denied" noisenpm run build 2>&1 | tee build.log # watch it live AND save a copyRedirects are processed left to right. 2>&1 means "point stderr at wherever stdout points right now". In the first line stdout already points at the file, so both go there. In the second, stdout still points at the screen when 2>&1 runs.
Match each task to the tool you would reach for first.
Make the shell yours: aliases, functions, dotfiles
Your shell runs a startup file every time a terminal opens: ~/.zshrc for zsh (the macOS default since 2019) and ~/.bashrc for bash (most Linux). Put shortcuts there:
alias gs='git status'alias ll='ls -lah'alias serve='python3 -m http.server 8000'# A function can take arguments, which an alias cannot.mkcd() { mkdir -p "$1" && cd "$1"; }# Kill whatever is listening on a port: killport 3000killport() { lsof -ti tcp:"$1" | xargs kill; }After editing, run source ~/.zshrc (or open a new terminal) to load the changes. Many engineers keep these files in a Git repository called dotfiles, so a new laptop is set up in minutes. Be careful not to commit secrets. API keys belong in a password manager or a .env file that is never committed, not in a public .zshrc.
Build the pipeline that prints the 5 most common HTTP status codes in a log (status is field 9). Put the stages in order.
- Tap the steps below in the right order.
- quoting
- Single quotes keep text literal. Double quotes expand
$VARbut keep the result as one argument. Quote every variable. - glob
- A filename pattern like
*.logthat the shell expands into matching names before the program runs. - word splitting
- bash re-splitting an unquoted variable on spaces, which breaks filenames that contain spaces. zsh does not do it by default.
- exit code
- The number a program returns: 0 for success, non-zero for failure.
$?holds the last one, and&&and||act on it. - stderr
- Stream 2, used for errors and progress.
2>&1sends it wherever stdout currently goes. - xargs
- Turns lines of input into arguments for another command. Use
-print0with-0to handle any filename safely. - dotfiles
- Configuration files like
~/.zshrc, often kept in a Git repo so a new machine is set up quickly.