Archives and disk tools

Linux commands: rmdir

Learn how the Linux rmdir command removes empty folders, one or many at a time, and why you need rm -rf instead to delete a folder that still has files.

rmdir removes empty directories. Create one and remove it:

mkdir fruits
rmdir fruits

No output means it worked. ls confirms the folder is gone.

It can remove several empty directories in one go:

mkdir fruits cars
rmdir fruits cars

The word that matters is empty. If a directory contains a file, another directory, or a hidden entry you don’t see with plain ls, rmdir refuses:

mkdir fruits
touch fruits/apple.txt
rmdir fruits
rmdir: failed to remove 'fruits': Directory not empty

On macOS the message is shorter, rmdir: fruits: Directory not empty, but the meaning is the same. Look inside to see what’s blocking it, including hidden files:

ls -la fruits

This refusal is a safety feature, not an annoyance. rmdir can never delete your data by accident, because it never deletes data at all.

To remove a folder with everything in it, you need rm -r. That’s a different, destructive operation. You’ll see rm -rf everywhere, and my advice is to not add -f out of habit: it suppresses prompts and some errors, which are the things that save you when the path is wrong.

Before any recursive deletion, I resolve and print the exact target first:

target="$PWD/build-output"
printf 'target: %s\n' "$target"
find "$target" -maxdepth 2 -print

Only go ahead once the printed path is the narrow one you expected and the listing shows what you meant to delete. Avoid unquoted variables, globs you have not previewed with echo, and running the command from a folder you’re not sure about. Deleting from the command line skips the desktop trash, so the only way back is a backup.

Some implementations support rmdir -p a/b/c, which removes c and then the empty parents b and a. Read man rmdir on the machine before using options in a script you want to be portable.

Try it yourself: create one empty directory and one containing a file, run rmdir on both, and notice which one is refused. That refusal is rmdir protecting the file.

Lesson completed