Removing Files and Directories Safely
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.
| Command | Removes | Needs |
|---|---|---|
rm file | Files | Write permission on the parent directory |
rmdir dir | Empty directories only | The directory must contain nothing |
rm -r dir | A directory and everything inside it | Write 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:
| Option | When it asks |
|---|---|
-i | Before every removal |
-I | Once, 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.