Every command belongs to one of four classes. Read-only commands only look. Reversible ones change something you can undo. Potentially destructive ones delete or overwrite. Privileged ones run with power over the whole machine or cluster. Experienced engineers classify a command before pressing Enter, check where they are, preview what it will touch, keep a way back, and use the least privilege that works. This lesson follows one routine cleanup of old log files through those habits, and shows the two classic accidents: a delete that ran in the wrong folder, and a privileged command with one stray space.
Difficulty: Beginner · Know this first: Lesson 03, Lesson 07
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes for one routine cleanup, including the checks. It is a worked example, not a measurement. The "where am I" and least-privilege hops decide whether a routine command stays routine.
Pick how the steps are joined, whether you preview first, and how much privilege you use.
Three questions. No score is saved anywhere — this is just you against the material.
Command safety grows in four levels: knowing the classes, habits for every risky command, guards built into scripts, and systems that make mistakes hard.
At the basic level you know what a command can change before you run it.
Where it breaks: pasted commands run without reading.
Try it: Basic
Which class is kubectl get pods?
Now do it: Classify five commands you used today.
At the intermediate level risky commands follow a routine.
Try it: Intermediate
kubectl diff -f app.yaml shows changes you did not expect. What now?
Now do it: Run kubectl diff before your next apply.
At the advanced level scripts refuse to do damage.
Try it: Advanced
Your cleanup script takes a directory as an argument. What stops it deleting / if the argument is empty?
Now do it: Add guards to one cleanup script.
At the master level the system limits what a mistake can do.
Trade-off: guard rails slow down the expert in a hurry; the hurry is exactly when they matter.
Try it: Master
What turns "someone deleted the bucket" from a disaster into an inconvenience?
Now do it: Check deletion protection on one important resource.
Previews for common destructive operations:
find /var/log/app -name '*.log' -mtime +7 -print # then the same with -delete rsync -a --delete --dry-run src/ dst/ # lines starting "deleting" are what would go kubectl delete -f app.yaml --dry-run=server # validated by the API server, nothing deleted kubectl diff -f app.yaml # what apply would change terraform plan # read the "to destroy" count git clean -n # -n lists what git clean -f would delete SELECT COUNT(*) FROM orders WHERE created < '2025-01-01'; -- before the DELETE with the same WHERE
A guarded delete in a script: rm -rf -- "${TARGET:?}"/old stops if TARGET is unset or empty, and -- stops a file name beginning with a dash from being read as an option. GNU rm refuses rm -rf / by default (--preserve-root), but not rm -rf /*, which the shell expands to every top-level folder before rm sees it.
Recovering from a recursive chown or chmod on a running system is rarely complete; package managers can restore ownership of packaged files, but not of everything else. Rebuilding from an image is usually faster and safer, which is one reason servers should be rebuildable.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. One space.
Permission fixes go through configuration management; recursive privileged commands are previewed with echo in the team runbook; servers can be rebuilt in under an hour; and a second person reads any recursive privileged command on production.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A Linux shell with GNU find, rsync (sudo apt install -y rsync), and Python 3. On macOS, touch -d and find -newermt differ; use the Linux shell in a container or VM, or read along.
Type each one, read what it prints, and compare it with the note above it.
Make a practice folder with log files of known ages (touch -d sets a file's date).
mkdir -p ~/labs/safe/logs && cd ~/labs/safe for d in 01 02 03 20 25; do touch -d "2026-11-$d 12:00" logs/app-$d.log; done ls logs
Preview: list the logs older than 21 November, exactly as the delete will select them.
find logs -name '*.log' ! -newermt "2026-11-21" -print | sort
Back up, delete with the same expression, and verify against the preview.
cp -a logs logs.bak && ls logs.bak | wc -l find logs -name '*.log' ! -newermt "2026-11-21" -delete ls logs
A dry run for a sync that deletes: rsync --delete removes files in the destination that the source does not have.
mkdir -p src dst && touch src/a src/b dst/a dst/old rsync -a --delete --dry-run -v src/ dst/ | grep -E '^(deleting|b$)' ls dst
Why && matters after cd. Nothing is deleted here: the dangerous command is replaced by a message saying where it would have run.
cd ~/labs/safe/does-not-exist; echo "after a failed cd with ;, rm -rf * would run in: $(pwd)" cd ~/labs/safe/does-not-exist && echo "never printed"; echo "with &&, the next command did not run; still in: $(pwd)"
Are you root? In WSL the default user may be root, which makes every command privileged.
id -u [ "$(id -u)" -eq 0 ] && echo "you are root: every command is privileged" || echo "normal user: use sudo for single commands only"
Clean up.
cd ~ && rm -rf ~/labs/safe ls ~/labs
classify.pyThis program sorts commands into the four safety classes with a small rule table, the way a team might lint the commands in its runbooks, and prints what to do before running each one. Real classification needs judgement; the rules show the idea. Save it as classify.py, then run it.
# classify.py
import re
RULES = [ # (class, pattern); the first match from the top wins, so privileged is checked first
("privileged", r"^(sudo|doas)\b|\bsu -|--as=system:admin|cluster-admin"),
("destructive", r"\brm\b|\bdd\b|\bmkfs|>\s*\S|\bdelete\b|\bdestroy\b|\breset --hard\b|\bclean -f|\bdrop\b|\btruncate\b|\bprune\b"),
("reversible", r"\bmkdir\b|\bcp\b|\bmv\b|\bswitch\b|\bscale\b|\bapply\b|\bcreate\b|\btouch\b|\bset-context\b"),
("read-only", r"."),
]
BEFORE = {
"read-only": "run it",
"reversible": "know the undo",
"destructive": "check where you are, preview, back up",
"privileged": "preview, elevate this one command, second reader on production",
}
def classify(cmd):
for cls, pattern in RULES:
if re.search(pattern, cmd, re.IGNORECASE):
return cls
for cmd in ["ls -la /var/log", "kubectl get pods -A", "git switch -c fix-login",
"kubectl scale deploy/api --replicas=3", "rm -rf build/", "echo hi > notes.txt",
"terraform destroy", "psql -c 'DROP TABLE orders'", "sudo chown -R app:app /var/lib/app",
"docker system prune -a"]:
cls = classify(cmd)
print(f"{cls:<12} {cmd:<38} -> {BEFORE[cls]}")
Run it, and you should see this output:
$ python3 classify.py read-only ls -la /var/log -> run it read-only kubectl get pods -A -> run it reversible git switch -c fix-login -> know the undo reversible kubectl scale deploy/api --replicas=3 -> know the undo destructive rm -rf build/ -> check where you are, preview, back up destructive echo hi > notes.txt -> check where you are, preview, back up destructive terraform destroy -> check where you are, preview, back up destructive psql -c 'DROP TABLE orders' -> check where you are, preview, back up privileged sudo chown -R app:app /var/lib/app -> preview, elevate this one command, second reader on production destructive docker system prune -a -> check where you are, preview, back up
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/safe-commands-read-only-reversible-destructive-and-privileged && cd ~/labs/safe-commands-read-only-reversible-destructive-and-privileged) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Safe Commands: Read-Only, Reversible, Destructive, and Privileged — Previews, Backups, and Cleanup", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Make a practice folder with log files of known ages (touch -d sets a file'\''s date).'
'Preview: list the logs older than 21 November, exactly as the delete will select them.'
'Back up, delete with the same expression, and verify against the preview.'
'A dry run for a sync that deletes: rsync --delete removes files in the destination that the source does not have.'
'Why && matters after cd. Nothing is deleted here: the dangerous command is replaced by a message saying where it would have run.'
'Are you root? In WSL the default user may be root, which makes every command privileged.'
'Clean up.'
)
step_1() {
mkdir -p ~/labs/safe/logs && cd ~/labs/safe
for d in 01 02 03 20 25; do touch -d "2026-11-$d 12:00" logs/app-$d.log; done
ls logs
}
step_2() {
find logs -name '*.log' ! -newermt "2026-11-21" -print | sort
}
step_3() {
cp -a logs logs.bak && ls logs.bak | wc -l
find logs -name '*.log' ! -newermt "2026-11-21" -delete
ls logs
}
step_4() {
mkdir -p src dst && touch src/a src/b dst/a dst/old
rsync -a --delete --dry-run -v src/ dst/ | grep -E '^(deleting|b$)'
ls dst
}
step_5() {
cd ~/labs/safe/does-not-exist; echo "after a failed cd with ;, rm -rf * would run in: $(pwd)"
cd ~/labs/safe/does-not-exist && echo "never printed"; echo "with &&, the next command did not run; still in: $(pwd)"
}
step_6() {
id -u
[ "$(id -u)" -eq 0 ] && echo "you are root: every command is privileged" || echo "normal user: use sudo for single commands only"
}
step_7() {
cd ~ && rm -rf ~/labs/safe
ls ~/labs
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, sort, wc, find, rsync, mkdir, rm, cp, Pipes, Loops, If...Else.Write the "safe commands" section of your team's operations handbook, for people new to production access.
How are commands classified? What checks come before destructive and privileged commands? Which previews do your tools offer? How are backups confirmed? When is a second person needed? What do scripts do to protect themselves? How is elevated access granted and logged?
Say 30 engineers with production access across Linux servers, two Kubernetes clusters, one cloud account, and PostgreSQL.
The four classes with examples per tool; a checklist (read, classify, locate, preview, back up, least privilege, watch, verify, record); previews per tool (find -print, rsync --dry-run, kubectl diff and --dry-run=server, terraform plan, SELECT before DELETE); a second reader for recursive privileged commands and deletions in production; script guards (set -euo pipefail, :? guards, dry-run defaults); time-limited, logged elevation; deletion protection and tested restores.
Checklists and second readers slow down routine work; apply them in proportion to the class of command, so read-only work stays fast.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Wrong folder | Hop 3: Where am I | Breaks | The folder is /var/log/app, typed as /var/log/ap. cd fails with "No such file or directory", but the semicolon runs rm -rf * anyway, in the current folder: the engineer's home folder, with two projects not yet pushed. |
| Wrong folder | Hop 7: Run | Breaks | Two projects and their uncommitted work are deleted. Restoring from last week's backup and redoing the lost work takes 90 minutes. |
| Privileged typo | Hop 4: Preview | Degrades | No preview. An echo of the command would have shown three arguments: app:app, /, and var/lib/app. |
| Privileged typo | Hop 6: Least privilege | Breaks | sudo with -R and a stray space between / and var/lib/app: chown receives / as a target and walks the entire filesystem. |
| Privileged typo | Hop 7: Run | Breaks | With sudo broken and ownership wrong across the system, there is no safe repair; the server is drained, rebuilt from its image, and returned to service: four hours. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.