Removing Files and Directories Safely

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 18 of 205

Deleting from the command line is quick and, on most systems, permanent. There is no recycle bin behind rm: when a file is removed, its name disappears from the directory immediately, and recovering the content is difficult or impossible. This lesson covers the commands that delete items (rm and rmdir), the options that add a confirmation step, and the habits that keep a typing slip from becoming a disaster.

Understanding the Concept

Removing a file means deleting its directory entry. When the last name that points to the data is gone, the file system marks the space as free. Because Bash runs the command exactly as typed, with no undo, the safest approach is to make every removal visible before it happens.

CommandRemovesNeeds
rm fileFilesWrite permission on the parent directory
rmdir dirEmpty directories onlyThe directory must contain nothing
rm -r dirA directory and everything inside itWrite permission along the tree

Removing Files with rm

touch a.txt b.txt c.log
rm a.txt
ls

Output:

b.txt  c.log

rm prints nothing on success, which fits the Unix tradition of silence when all is well. The -v option (verbose) reports each removal:

rm -v b.txt

Output:

removed 'b.txt'

Missing Files

Removing a name that does not exist is an error:

rm nosuch
echo "status=$?"

Output:

rm: cannot remove 'nosuch': No such file or directory
status=1

The option -f (force) ignores missing files and never prompts. The status is then 0:

rm -f nosuch
echo "status=$?"

Output:

status=0

The -f option is useful in scripts that clean up, where it does not matter whether the file was there. It also removes the protection of any prompt, so treat it with care, especially when combined with -r.

Removing Directories

rmdir for Empty Directories

rmdir is the cautious tool. It refuses to remove a directory that holds anything:

mkdir emptydir
mkdir -p full/sub
touch full/sub/f.txt
rmdir emptydir
echo "status=$?"
rmdir full
echo "status=$?"

Output:

status=0
rmdir: failed to remove 'full': Directory not empty
status=1

The empty directory was removed, but rmdir refused to touch full. Because a mistake can only remove an empty directory, rmdir is safe to run when you are unsure. The option -p removes a chain of empty parents, so rmdir -p p/q/r removes r, then q, then p.

rm -r for Directories With Content

Plain rm will not remove a directory:

mkdir emptydir2
rm emptydir2

Output:

rm: cannot remove 'emptydir2': Is a directory

The option -r (recursive) removes the directory and everything beneath it. Adding -v lists each item as it goes:

mkdir tree
touch tree/1 tree/2 tree/3
rm -rv tree

Output:

removed 'tree/3'
removed 'tree/2'
removed 'tree/1'
removed directory 'tree'

Files are removed first and the directory last, because a directory must be empty before the system will delete it. The order of the files inside the directory can differ from one machine to another. The option -d is a middle ground: rm -d dir removes an empty directory, like rmdir.

Asking Before Removing

Two options add a confirmation prompt:

OptionWhen it asks
-iBefore every removal
-IOnce, before removing more than three files or when using -r

With -i, the command asks about each file in turn. Answer y to delete and anything else to keep:

touch f1 f2 f3
rm -i f1 f2 f3

Interactive session:

rm: remove regular empty file 'f1'? y
rm: remove regular empty file 'f2'? n
rm: remove regular empty file 'f3'? y

After this session only f2 is left. The word empty appears because these test files have no content. For a file with content, the prompt reads remove regular file.

The option -I is a lighter safety net that does not interrupt every file:

touch g1 g2 g3 g4
rm -I g1 g2 g3 g4

Interactive session:

rm: remove 4 arguments? y

One question covers the whole command. When you use -I you notice the number of arguments, which is often exactly the clue that a wildcard matched more than you expected.

Handling Difficult Names

Names That Start With a Dash

A file named -weird looks like an option to rm:

touch ./-weird
rm -weird

Output:

rm: invalid option -- 'w'

There are two fixes. Put -- before the names, which tells the command that no more options follow, or give the name a path such as ./-weird:

rm -- -weird

The command succeeds and prints nothing.

Names With Spaces

Without quotes, a name with a space is split into two arguments, and rm tries to remove two files that probably do not exist:

touch "my file.txt"
rm my file.txt

Output:

rm: cannot remove 'my': No such file or directory
rm: cannot remove 'file.txt': No such file or directory

This time nothing was lost, but the same mistake can delete the wrong thing when a file called my really exists. Quote the name instead:

rm "my file.txt"

Making Removal Safer

Look Before You Delete

Wildcards such as *.log are expanded by the shell, which means you can see what they will match before running rm. Put echo in front of the command to print the final command instead of running it:

touch d1.log d2.log keep.txt
echo rm *.log

Output:

rm d1.log d2.log

The shell expanded *.log into two names, so the real command would remove those two files and leave keep.txt alone. Once the list looks right, run the same command without echo. Another way to preview is to run ls with the same pattern:

ls *.log
rm *.log
ls

Output:

d1.log  d2.log
keep.txt

Guard Against Empty Variables

The most dangerous removals involve variables. If DIR is empty or unset, the command rm -rf "$DIR"/* expands to rm -rf /*, which targets the top of the file system. Bash can stop the command when a variable is empty, using the expansion ${VAR:?message}. It prints the message and does not run the command that contains it. This example shows the guard on its own, with : (a command that does nothing) in place of rm:

unset DIR
: "${DIR:?DIR is not set}"

Output in an interactive shell:

bash: DIR: DIR is not set

In a script, this error also ends the script. Writing rm -rf "${DIR:?DIR is not set}"/* therefore removes nothing at all when DIR is missing. GNU rm also refuses to operate on / itself by default, but this protection does not extend to /* or to your home directory, so the guard is still your job.

Move Instead of Delete

When you are not certain, move the item aside instead of removing it. The mv command from the previous lesson makes this easy:

mkdir -p .trash
touch junk
mv junk .trash/
ls -A .trash

Output:

junk

The file is out of the way but still recoverable. Delete the .trash directory later, once you are sure you no longer need it. This approach needs no extra software, so it works on any machine.

Practical Applications

Cleaning Up Temporary Files

A script can remove its own temporary files with a pattern, preceded by a preview during development:

touch t1.tmp t2.tmp
ls *.tmp
rm *.tmp

Output:

t1.tmp  t2.tmp

Because the pattern ends in .tmp, only temporary files are matched. The ls line confirms the match before rm runs, and rm *.tmp prints nothing.

Removing a Directory Tree You Created

A script that builds a working directory should remove exactly that directory when it finishes:

workdir="build_output"
mkdir -p "$workdir"
touch "$workdir/result.txt"
rm -r "${workdir:?}"
ls -d "$workdir" 2>&1

Output:

ls: cannot access 'build_output': No such file or directory

The expansion ${workdir:?} makes rm fail if the variable ever becomes empty, and the quotes keep a name with spaces in one piece. The last line proves the directory is gone.

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 Removing Files and Directories Safely and get answers drawn from it.

Signed-in readers only.