Skip to content

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.

22 min read0/5 questions

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:

KeysDoes
Ctrl+A / Ctrl+EJump to the start / end of the line
Ctrl+UDelete everything before the cursor
Ctrl+WDelete the previous word
Ctrl+RSearch 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.

What the shell does to one command line
  1. 1. Split into wordsspaces separate words, quotes group them
  2. 2. Expand $VAR and $(command)inside double quotes too, never inside single
  3. 3. Re-split unquoted results (bash)the step that breaks filenames with spaces
  4. 4. Expand globs like *.logthe shell matches files, not the program
  5. 5. Set up redirects, then runthe program gets a clean 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.

1/5

Python's shlex module splits a line with the same rules as step 1, so you can see what a program would receive:

Python
import shlex lines = [ 'rm my notes.txt', 'rm "my notes.txt"', "echo 'Hi $USER' \"Hi $USER\"", 'grep -rn "TODO: fix" src',]# shlex only splits (step 1). The real shell would then expand $USER# inside the double quotes, but leave the single-quoted one alone.for line in lines: print(f"{line!s:32} -> {shlex.split(line)}")
Output
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 $VAR and $(...), 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, **/*.py searches every subfolder. In bash it needs shopt -s globstar, which only exists in bash 4 and later.
Quick check
In a bash script on Linux, f="Q3 report.pdf", and the folder contains Q3, report.pdf and Q3 report.pdf. What does rm $f delete?
Need a nudge? A hint rules out a wrong answer.

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:

ToolJobExample
grepKeep lines that matchgrep -v DEBUG app.log (-v inverts)
sortSort linessort -n numeric, -r reverse, -k2 by column 2
uniq -cCount adjacent repeatsalways after sort
wc -lCount linesgrep -c counts matches directly
head / tailFirst / last linestail -n 100, tail -f to follow
cutPick columns by a delimitercut -d, -f2 users.csv
trTranslate or delete characterstr 'a-z' 'A-Z', tr -d '\r'
sedFind and replace in a streamsed 's/http:/https:/g'
awkColumns split on whitespace, plus logicawk '$9 >= 500'
lessRead 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 10
Top IPs in an access log
access.log: one request per lineaccess.logone request per lineawk '{print $1}': keep the IPawk '{print $1}'keep the IPsort: group equal IPssortgroup equal IPsuniq -c: count each rununiq -ccount each runsort -rn: biggest firstsort -rnbiggest firsthead -n 10: top tenhead -n 10top tenlinesIPssorted IPscount + IPranked

awk prints field 1 of every line, so 2 GB of log becomes a column of IP addresses.

1/5

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:

Python
from collections import Counter log = """203.0.113.7 - - "GET / HTTP/1.1" 200198.51.100.23 - - "GET /login HTTP/1.1" 200203.0.113.7 - - "POST /login HTTP/1.1" 302192.0.2.44 - - "GET /admin HTTP/1.1" 404203.0.113.7 - - "GET /dashboard HTTP/1.1" 200192.0.2.44 - - "GET /.env HTTP/1.1" 404""" ips = [line.split()[0] for line in log.splitlines()] # awk '{print $1}'print("awk: ", ips) # uniq -c only merges ADJACENT duplicates. Without sort first, it miscounts.def uniq_c(items): out = [] for item in items: if out and out[-1][1] == item: out[-1][0] += 1 else: out.append([1, item]) return out print("uniq -c: ", uniq_c(ips))print("sort|uniq:", uniq_c(sorted(ips)))ranked = sorted(uniq_c(sorted(ips)), key=lambda p: p[0], reverse=True) # sort -rnprint("top: ", ranked[:2]) # head -n 2print("Counter: ", Counter(ips).most_common(2))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputShell

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
Need a nudge? Hints walk you through it.

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 default

And 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.bak

Finding 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 ones

Quote 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 itself

The 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 what

a && 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.

Quick check
npm test && git push || echo 'tests failed'. The tests pass but the push is rejected by the server. What happens?
Need a nudge? A hint rules out a wrong answer.

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 copy

Redirects 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 the pairs0/6 matched

Match each task to the tool you would reach for first.

Choose an item, then its match on the other side.

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:

~/.zshrc
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.

Put it in order5 steps

Build the pipeline that prints the 5 most common HTTP status codes in a log (status is field 9). Put the stages in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
quoting
Single quotes keep text literal. Double quotes expand $VAR but keep the result as one argument. Quote every variable.
glob
A filename pattern like *.log that 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>&1 sends it wherever stdout currently goes.
xargs
Turns lines of input into arguments for another command. Use -print0 with -0 to handle any filename safely.
dotfiles
Configuration files like ~/.zshrc, often kept in a Git repo so a new machine is set up quickly.