Skip to content

rm

Practical examples of the rm command, covering safe deletion, recursive removal, exclusions, edge cases, and defensive usage patterns


Delete a simple file

rm

Delete a folder

rm -rf

Delete a file or folder with verbose on

rm -vrf path/filename

Delete all files in a folder that don't match a certain file extension

rm !(*.foo|*.bar|*.baz)

Remove all but one specific file

rm -f !(filename.txt)

Remove all files previously extracted from a tar(.gz) file

tar -tf <file.tar.gz> | xargs rm -r

Delete all folders regardless of content, use rm -rf with find.

find /path/to/parent -type d -exec rm -rf {} +

Remove directories bottom-up (prevents “not empty” errors)

find /path/to/parent -type d -depth -exec rmdir {} +

Remove only empty directories

find /path/to/parent -type d -empty -delete

Remove everything except the top-level directory

find /path/to/parent -mindepth 1 -exec rm -rf {} +

Remove everything except the top-level directory (more ffciently then above)

rm -rf /path/to/parent/*
rm -rf /path/to/parent/.[!.]*

Delete a path or filename under ---

Use – (the canonical solution)

rm -- ---

Use a relative path

rm ./---

Be extra defensive

rm -i -- ---