Safe Use of rm and Destructive Commands
A destructive command is any command that removes or overwrites data in a way that cannot be undone: rm, rm -r, find -delete, mv and cp onto an existing file, the > redirection, truncate, dd, mkfs, git clean, git reset --hard, docker system prune and many more. On Linux there is no recycle bin for these commands. When rm removes a file, the data is gone unless a backup exists.
In an interactive shell, you see the command before you press Enter. In a script, the command is built from variables, globs and the output of other commands, and it runs without anyone checking it. Most real disasters caused by shell scripts are not exotic attacks; they are an empty variable, a failed cd, a file name that starts with a dash or a find expression in the wrong order. This lesson shows each of these failures safely, using echo and test folders, and then the techniques that prevent them.
Understanding the Concept
A destructive command in a script is dangerous when its target can be different from what the author intended. The target is usually assembled at run time:
rm -rf -- "$build_dir/"*
This one line depends on four things being right: build_dir is set, it is not empty, it points to the intended folder, and the glob expands to what you expect. Safe scripts make each of those conditions checked instead of assumed, and they add layers that limit the damage when a check is missing: dry runs, confirmations, a trash folder instead of deletion, and running as a user who cannot touch important files (lesson 159).
The Empty Variable
The classic failure is a variable that is unexpectedly empty or unset. The following script uses echo to show the command it would run:
build_dir=''
echo rm -rf "$build_dir/"
echo rm -rf "${build_dir:?}/"
echo "not reached"
rm -rf /
t1.sh: line 4: build_dir: parameter null or not set
(The test scripts t1.sh, t2.sh and t3.sh in this lesson each start with one extra line that prints a heading, so the line numbers in their error messages are one higher than in the snippets shown. The script stopped at the :? line with status 1.)
With an empty build_dir, the path "$build_dir/" becomes /, the root of the file system. GNU rm refuses rm -rf / by default (its --preserve-root behavior), but it does not protect against "$build_dir/"*, which expands to /bin /boot /etc ..., or against "$build_dir/home" and similar paths.
The expansion ${build_dir:?} stops the script with an error when the variable is unset or empty (lesson 45). Use it in every destructive command that contains a variable, even when you are sure the variable is set: it documents the assumption and enforces it. An optional message can follow the ?, as in ${build_dir:?build_dir is not set}.
set -u (lesson 120) catches a second kind of mistake, a misspelled variable name:
set -u
echo rm -rf "$buld_dir/"
t2.sh: line 3: buld_dir: unbound variable
Without set -u, the misspelled $buld_dir would silently expand to nothing. set -u does not catch a variable that is set to an empty string; that is what :? is for. Use both.
The Failed cd
Many scripts change into a folder and then remove "everything here":
cd "$cache_dir"
rm -rf ./*
If cd fails, because the folder was renamed, the disk is not mounted or the variable is wrong, the script continues in the folder it was already in, and rm empties that folder instead. This script was started in /srv/t160:
cd /nonexistent-folder
pwd
cd /nonexistent-folder || { echo "stopping: cannot enter folder" >&2; exit 1; }
t3.sh: line 2: cd: /nonexistent-folder: No such file or directory
/srv/t160
t3.sh: line 4: cd: /nonexistent-folder: No such file or directory
stopping: cannot enter folder
After the first cd failed, pwd still printed the starting folder; an rm -rf ./* on the next line would have run there. Always write cd "$dir" || exit 1 (or rely on set -e, lesson 119). Better still, avoid cd before destructive commands and use full paths, so the target does not depend on the current folder at all.
File Names That Look Like Options
A glob expands to file names, and a file name can start with -. In a folder containing the files -rf, a.txt and b.txt:
echo rm *
echo rm -- *
echo rm ./*
rm -rf a.txt b.txt
rm -- -rf a.txt b.txt
rm ./-rf ./a.txt ./b.txt
The plain rm * would receive -rf as options, so it would remove a.txt and b.txt recursively and without asking, and leave the file -rf in place. -- marks the end of options, so every following argument is a file name. Prefixing globs with ./ has the same effect and also helps other commands that do not support --. Use both habits with every destructive command: rm -- "$file", rm -f -- ./*.tmp.
find Expressions in the Wrong Order
find evaluates its expression from left to right, and actions such as -print and -delete run as soon as they are reached. In the folder f, which contains keep.txt, x.tmp and y.tmp:
find f -print -name '*.tmp'
find f -name '*.tmp' -print
f
f/keep.txt
f/x.tmp
f/y.tmp
f/x.tmp
f/y.tmp
With -print first, every file was printed, because the -name test came after the action. With -delete in that position, find f -delete -name '*.tmp' would delete everything under f, including f itself. Always put tests before actions, and always run the command with -print first, check the list, and only then replace -print with -delete.
Interactive Safety Options
rm has options that ask before removing:
-iasks before every file. That is too many prompts for large jobs, so people learn to answerywithout reading.-Iasks once when removing more than three files or when removing recursively, showing the number of arguments.
printf 'n\n' | rm -rI old-logs; echo "status $?"
printf 'n\n' | rm -I r1 r2 r3 r4; echo "status $?"
rm: remove 1 argument recursively? status 0
rm: remove 4 arguments?
status 0
In both cases the answer n cancelled the removal and the files remained, but notice that rm still returned status 0. A script cannot use the status to learn whether the user cancelled. These options are useful at the interactive prompt; in scripts, an explicit confirmation step that you control works better (see the complete example).
Overwriting Files
Removal is not the only way to lose data. Redirection with >, mv and cp replace existing files silently.
Redirection and noclobber
set -C (also written set -o noclobber, lesson 148) makes > refuse to overwrite an existing file. >| overwrites deliberately:
printf 'important\n' > data.txt
set -C
echo new > data.txt; echo "status $?"
echo new >| data.txt; cat data.txt
noclobber.sh: line 3: data.txt: cannot overwrite existing file
status 1
new
mv and cp
mv -n (no clobber) refuses to replace an existing target. In the GNU coreutils version used here (9.4), it also prints a message and returns status 1, so a script can react:
printf 'keep\n' > target; printf 'other\n' > src
mv -n src target; echo "status $?"
cat target
mv: not replacing 'target'
status 1
keep
Older coreutils versions returned 0 in this situation, so check the behavior of the systems your script runs on. When a file must be replaced but the old version should be kept, --backup=numbered renames the existing file first:
printf 'v1\n' > conf; printf 'v2\n' > conf.new
cp --backup=numbered conf.new conf
cp --backup=numbered conf.new conf
ls conf*
conf
conf.new
conf.~1~
conf.~2~
Each copy saved the previous conf as a numbered backup instead of destroying it.
Checking That a Path Is Where You Expect
A path that arrives from an argument or a configuration file can point anywhere: .. components, symbolic links and absolute paths can all lead outside the intended folder. Before destroying anything, resolve the path to its real location and confirm that it lies inside an allowed base folder:
target=$(realpath -e -- "$1") || exit 1
[[ $target != "$base" && $target == "$base"/* ]] || exit 1
realpath -e resolves ., .. and symbolic links, and fails if the path does not exist. The comparison then requires the result to be strictly inside the base folder. The /* after "$base" matters: without the slash, /srv/cache-old would pass a check for /srv/cache. Lesson 161 covers path validation in more depth.
Layers of Protection
No single technique prevents every mistake, so careful scripts combine several:
| Layer | What it prevents |
|---|---|
set -euo pipefail, ${var:?} | running with missing or empty values |
cd ... || exit, or no cd at all | acting in the wrong folder |
-- and ./ before globs | names being read as options |
realpath plus a base-folder check | paths leaving the intended folder |
tests before actions in find; -print before -delete | matching more than intended |
dry run by default, explicit --apply | surprises on the first run |
| a confirmation for people, a flag for automation | accidental runs at the terminal |
| moving to a trash folder | permanent loss of something still needed |
| a dedicated low-privilege user | damage outside the job's own files |
A Complete Example: A Safe Cleanup Tool
safe-clean.sh removes files older than a given number of days from a folder. It only works inside one allowed base folder, does nothing unless --apply is given, asks a person at a terminal to type yes, and can move files to a trash folder instead of deleting them.
#!/usr/bin/env bash
# safe-clean.sh: remove old files from a folder inside an allowed base folder
# usage: safe-clean.sh [--apply] [--days N] [--trash] DIR
# default is a dry run that only lists what would be removed
# --trash moves files into DIR/../.trash-YYYYmmdd-HHMMSS instead of deleting
set -euo pipefail
readonly BASE=${CLEAN_BASE:-/srv/t160/cache} # only folders under here
apply=0 trash=0 days=30
die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 2; }
while (( $# > 0 )); do
case $1 in
--apply) apply=1 ;;
--trash) trash=1 ;;
--days) (( $# >= 2 )) || die '--days needs a number'; days=$2; shift ;;
--) shift; break ;;
-*) die "unknown option: ${1@Q}" ;;
*) break ;;
esac
shift
done
(( $# == 1 )) || die 'usage: safe-clean.sh [--apply] [--days N] [--trash] DIR'
[[ $days =~ ^[0-9]{1,4}$ ]] && (( 10#$days >= 1 )) || die "--days must be 1-9999: ${days@Q}"
days=$((10#$days))
# 1. Resolve the real target and make sure it is a folder strictly inside BASE
[[ -n $1 ]] || die 'DIR must not be empty'
base_real=$(realpath -e -- "$BASE") || die "base folder missing: $BASE"
target=$(realpath -e -- "$1") || die "no such folder: ${1@Q}"
[[ -d $target ]] || die "not a folder: ${target@Q}"
[[ $target != "$base_real" ]] || die "refusing the base folder itself: $base_real"
[[ $target == "$base_real"/* ]] || die "refusing ${target@Q}: not inside $base_real"
# 2. Collect regular files older than DAYS days, NUL-separated, never following links
files=()
while IFS= read -r -d '' f; do
files+=("$f")
done < <(find "$target" -xdev -type f -mtime +"$days" -print0 | LC_ALL=C sort -z)
if (( ${#files[@]} == 0 )); then
echo "nothing older than $days day(s) in $target"
exit 0
fi
bytes=$(du -cb -- "${files[@]}" | tail -n 1 | cut -f1)
printf '%d file(s), %d bytes older than %d day(s) in %s:\n' "${#files[@]}" "$bytes" "$days" "$target"
printf ' %q\n' "${files[@]#"$target"/}"
# 3. Dry run unless --apply was given
if (( ! apply )); then
echo "dry run: nothing removed (use --apply to remove)"
exit 0
fi
# 4. A person at a terminal must confirm; scripts (no terminal) rely on --apply
if [[ -t 0 ]]; then
read -r -p "Remove these ${#files[@]} file(s)? Type yes: " answer
[[ $answer == yes ]] || die 'cancelled'
fi
if (( trash )); then
trash_dir=$(dirname -- "$target")/.trash-$(date +%Y%m%d-%H%M%S)
for f in "${files[@]}"; do
rel=${f#"$target"/}
mkdir -p -- "$trash_dir/$(dirname -- "$rel")"
mv -n -- "$f" "$trash_dir/$rel"
done
echo "moved ${#files[@]} file(s) to $trash_dir"
else
rm -f -- "${files[@]}"
echo "removed ${#files[@]} file(s)"
fi
How It Works
- Strict mode.
set -euo pipefailstops the script on unexpected failures and on misspelled variables. - Options. The loop accepts only the three known options and
--. Anything else that starts with-, such as-rf, is refused rather than ignored.--daysmust be 1 to 4 digits and at least 1;10#reads it as decimal even with leading zeros. - Fixed base folder.
BASEis set once at the top. An environment variable can change it for testing, but the script never works outside it. - Path checks. The target is resolved with
realpath -e, which follows..and symbolic links. It must be an existing folder, must not be the base folder itself and must be strictly inside it. A symbolic link inside the base that points elsewhere resolves to its real location and is refused. - Collecting files.
findlists only regular files (-type f) older than the given age.-xdevkeeps it on one file system, so a disk mounted inside the folder is not touched.finddoes not follow symbolic links by default. The names travel NUL-separated into an array (lesson 112), so spaces, newlines and leading dashes are handled. - Showing the plan. The script prints the number of files, their total size (
du -cbadds a total line) and each file relative to the target, quoted with%qso unusual names are visible. - Dry run by default. Without
--apply, the script stops after showing the plan. - Confirmation. When standard input is a terminal, a person must type the full word
yes. When the script runs from cron or another script, there is no terminal, and--applyalone is the explicit decision. - Trash or delete. With
--trash, files are moved into a time-stamped.trash-...folder next to the target, keeping their relative paths, andmv -nnever overwrites anything there. Otherwise,rm -f --removes exactly the collected list; no glob is expanded at removal time.
Running the Complete Example
The base folder /srv/t160/cache contains build/obj/main.o (45 days old), build/fresh.log (new), my downloads/-report 1.pdf (45 days old) and a symbolic link link-to-other that points to /srv/t160/other, which is outside the base.
A dry run lists what would be removed:
./safe-clean.sh cache/build; echo "status $?"
./safe-clean.sh --days 10 'cache/my downloads'; echo "status $?"
1 file(s), 5 bytes older than 30 day(s) in /srv/t160/cache/build:
obj/main.o
dry run: nothing removed (use --apply to remove)
status 0
1 file(s), 3 bytes older than 10 day(s) in /srv/t160/cache/my downloads:
-report\ 1.pdf
dry run: nothing removed (use --apply to remove)
status 0
The new file fresh.log was not listed. The file name with a leading dash and a space was shown quoted.
Dangerous or invalid targets are refused before anything is listed:
./safe-clean.sh cache; echo "status $?"
./safe-clean.sh other; echo "status $?"
./safe-clean.sh cache/build/../../other; echo "status $?"
./safe-clean.sh cache/link-to-other; echo "status $?"
./safe-clean.sh ''; echo "status $?"
./safe-clean.sh /; echo "status $?"
./safe-clean.sh --days 0 cache/build; echo "status $?"
./safe-clean.sh --days '1;id' cache/build; echo "status $?"
./safe-clean.sh -rf cache/build; echo "status $?"
safe-clean.sh: refusing the base folder itself: /srv/t160/cache
status 2
safe-clean.sh: refusing '/srv/t160/other': not inside /srv/t160/cache
status 2
safe-clean.sh: refusing '/srv/t160/other': not inside /srv/t160/cache
status 2
safe-clean.sh: refusing '/srv/t160/other': not inside /srv/t160/cache
status 2
safe-clean.sh: DIR must not be empty
status 2
safe-clean.sh: refusing '/': not inside /srv/t160/cache
status 2
safe-clean.sh: --days must be 1-9999: '0'
status 2
safe-clean.sh: --days must be 1-9999: '1;id'
status 2
safe-clean.sh: unknown option: '-rf'
status 2
The .. path and the symbolic link both resolved to /srv/t160/other and were refused, as were the empty argument, /, invalid ages and the option-like -rf.
With --apply and no terminal (as in cron), files are moved to the trash or removed:
./safe-clean.sh --apply --trash 'cache/my downloads' < /dev/null; echo "status $?"
find cache -path '*trash*' -type f
./safe-clean.sh --apply cache/build < /dev/null; echo "status $?"
find cache/build -type f
./safe-clean.sh --apply cache/build < /dev/null; echo "status $?"
ls other
1 file(s), 3 bytes older than 30 day(s) in /srv/t160/cache/my downloads:
-report\ 1.pdf
moved 1 file(s) to /srv/t160/cache/.trash-20261124-090451
status 0
cache/.trash-20261124-090451/-report 1.pdf
1 file(s), 5 bytes older than 30 day(s) in /srv/t160/cache/build:
obj/main.o
removed 1 file(s)
status 0
cache/build/fresh.log
nothing older than 30 day(s) in /srv/t160/cache/build
status 0
keep.txt
The old download went to the trash folder, where it can still be recovered. The old object file was removed, the new log file stayed, a second run found nothing to do, and other/keep.txt, although it is just as old, was never touched.
At a terminal, the script asks first. The next test used script to give it a pseudo-terminal and typed no, then yes, for a folder cache/tmp holding one old file. The first line of each output is the typed answer, echoed by the terminal:
no
1 file(s), 3 bytes older than 30 day(s) in /srv/t160/cache/tmp:
old.part
Remove these 1 file(s)? Type yes: safe-clean.sh: cancelled
yes
1 file(s), 3 bytes older than 30 day(s) in /srv/t160/cache/tmp:
old.part
Remove these 1 file(s)? Type yes: removed 1 file(s)
Answering no stopped the script with status 2 and kept the file; only the full word yes allowed the removal.