Safe Use of rm and Destructive Commands

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 160 of 205

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:

  • -i asks before every file. That is too many prompts for large jobs, so people learn to answer y without reading.
  • -I asks 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:

LayerWhat it prevents
set -euo pipefail, ${var:?}running with missing or empty values
cd ... || exit, or no cd at allacting in the wrong folder
-- and ./ before globsnames being read as options
realpath plus a base-folder checkpaths leaving the intended folder
tests before actions in find; -print before -deletematching more than intended
dry run by default, explicit --applysurprises on the first run
a confirmation for people, a flag for automationaccidental runs at the terminal
moving to a trash folderpermanent loss of something still needed
a dedicated low-privilege userdamage 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 pipefail stops 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. --days must be 1 to 4 digits and at least 1; 10# reads it as decimal even with leading zeros.
  • Fixed base folder. BASE is 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. find lists only regular files (-type f) older than the given age. -xdev keeps it on one file system, so a disk mounted inside the folder is not touched. find does 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 -cb adds a total line) and each file relative to the target, quoted with %q so 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 --apply alone 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, and mv -n never 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Safe Use of rm and Destructive Commands and get answers drawn from it.

Signed-in readers only.