Platform Engineering · Lesson 08

Safe Commands: Read-Only, Reversible, Destructive, and Privileged — Previews, Backups, and Cleanup

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: how safe is your cleanup?

Pick how the steps are joined, whether you preview first, and how much privilege you use.

stopsa typo in the path
your filesworst case reaches
yesway back

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Command safety grows in four levels: knowing the classes, habits for every risky command, guards built into scripts, and systems that make mistakes hard.

Basic — Know the classes

At the basic level you know what a command can change before you run it.

  • Read-only, reversible, potentially destructive, privileged.
  • pwd and hostname before anything that deletes.
  • Practice inside ~/labs.

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.

Intermediate — Habits for every risky command

At the intermediate level risky commands follow a routine.

  • Previews: -print, --dry-run, plan, diff, SELECT.
  • A checked backup before deleting.
  • && instead of ;, and full paths.

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.

Advanced — Guards in scripts

At the advanced level scripts refuse to do damage.

  • set -euo pipefail and :? guards on paths built from variables.
  • A --dry-run mode in your own tools, on by default for destructive actions.
  • Confirmation prompts that show the count and target.

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.

Master — Make mistakes hard

At the master level the system limits what a mistake can do.

  • Read-only defaults; elevation that is time-limited and logged.
  • Deletion protection, soft deletes, versioned buckets, and tested restores.
  • Changes through reviewed code and pipelines, not hand-typed commands.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. One space.

Timeline

  • 14:05To fix a permissions error, an engineer on app-server-3 types sudo chown -R app:app / var/lib/app, with a stray space after the first slash.
  • 14:06The command is slow, which is suspicious; Ctrl+C stops it, but /usr, /etc, and more now belong to app. sudo refuses to run.
  • 14:20The server is taken out of the load balancer, rebuilt from the standard image, and its data volume reattached.
  • 18:05Back in service after testing.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a practice folder with log files of known ages (touch -d sets a file's date).

    Reversible

    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

    Options: touch -d DATE creates a file (or sets its time) with that date; the loop makes five logs dated the 1st, 2nd, 3rd, 20th, and 25th.

    Expect: app-01.log app-02.log app-03.log app-20.log app-25.log.

    Clean up: cd ~ && rm -rf ~/labs/safe (the last step).

  2. Preview: list the logs older than 21 November, exactly as the delete will select them.

    Read-only

    find logs -name '*.log' ! -newermt "2026-11-21" -print | sort

    Options: -name '*.log' matches names (quoted so find, not the shell, expands it); ! -newermt DATE means "not modified after DATE"; -print lists matches. In real use, -mtime +7 means "older than seven days".

    Expect: Four files: logs/app-01.log, logs/app-02.log, logs/app-03.log, logs/app-20.log. The 25th is newer and is not listed.

  3. Back up, delete with the same expression, and verify against the preview.

    Potentially destructive

    cp -a logs logs.bak && ls logs.bak | wc -l
    find logs -name '*.log' ! -newermt "2026-11-21" -delete
    ls logs

    Options: cp -a copies with dates and permissions; -delete replaces -print, so the previewed list is what goes.

    Expect: 5 (all five backed up), then only app-25.log left, as the preview said.

    If it fails: If more went than expected, restore from the backup: cp -a logs.bak/. logs/.

  4. A dry run for a sync that deletes: rsync --delete removes files in the destination that the source does not have.

    Read-only

    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

    Options: -a archive mode; --delete removes extra files from the destination; --dry-run (or -n) only reports; -v lists each action. The trailing slashes mean "the contents of".

    Expect: deleting old and b (what would happen), then ls dst still shows a and old: nothing changed.

  5. Why && matters after cd. Nothing is deleted here: the dangerous command is replaced by a message saying where it would have run.

    Read-only

    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)"

    Expect: cd: … No such file or directory twice. The first line still runs and prints your current folder (…/labs/safe): that is where rm -rf * would have run. With &&, "never printed" is not printed.

  6. Are you root? In WSL the default user may be root, which makes every command privileged.

    Read-only

    id -u
    [ "$(id -u)" -eq 0 ] && echo "you are root: every command is privileged" || echo "normal user: use sudo for single commands only"

    Options: id -u prints your user ID; 0 is root.

    Expect: 1000 (or similar) and "normal user", or 0 and "you are root". If you are root in WSL, create a normal user (sudo adduser yourname, then set it as the default with wsl --manage Ubuntu --set-default-user yourname in PowerShell, or in /etc/wsl.conf).

  7. Clean up.

    Potentially destructive

    cd ~ && rm -rf ~/labs/safe
    ls ~/labs

    Expect: No error; safe is gone. A destructive command, made safe by a full path inside ~/labs and && after cd.

2. Python: classify.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Write the "safe commands" section of your team's operations handbook, for people new to production access.

Clarifying questions to ask

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?

Rough sizing

Say 30 engineers with production access across Linux servers, two Kubernetes clusters, one cloud account, and PostgreSQL.

Shape of the answer

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.

Trade-offs to name

Checklists and second readers slow down routine work; apply them in proportion to the class of command, so read-only work stays fast.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Wrong folderHop 3: Where am IBreaksThe 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 folderHop 7: RunBreaksTwo projects and their uncommitted work are deleted. Restoring from last week's backup and redoing the lost work takes 90 minutes.
Privileged typoHop 4: PreviewDegradesNo preview. An echo of the command would have shown three arguments: app:app, /, and var/lib/app.
Privileged typoHop 6: Least privilegeBreakssudo with -R and a stray space between / and var/lib/app: chown receives / as a target and walks the entire filesystem.
Privileged typoHop 7: RunBreaksWith 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.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Read it → Classify → Where am I → Preview → Backup → Least privilege → Run → Verify → Record. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 09
Linux for Engineers

A Linux server is a small set of ideas that show up everywhere: files live in fixed places, every file has an owner and a set of permissions, every running program is a process, and a service manager keeps the important processes…

Go to Lesson 09 →

Or browse the full course from the Lessons index.