How to Search and Remove Directories Recursively on Linux?

Removing directories is a regular process for anyone working on Unix systems. But sometimes we also need to find the directories first and then decide to delete them. One hurdle in deleting directories is doing recursive deletion because by default Unix systems do not allow deleting of a directory if it is not empty. In this article we will see how to find and remove directories recursively using two effective methods.

Using find and exec

The find command with -exec searches for directories and executes the removal command directly. This method is efficient for finding and deleting directories in one operation ?

$ find /path/to/search -name "Dir_name_to_delete" -type d -exec /bin/rm -rf {} +

Command Parameters

-type d         - restricts the search only to directories
-name "pattern" - specifies the directory name to search for
-exec           - executes an external command (rm -rf in this case)
{}              - placeholder for found directory paths
+               - appends multiple found paths to single rm command (more efficient)
-rf             - recursive and force removal options

Example

To find and remove all directories named "temp" under /home directory ?

$ find /home -name "temp" -type d -exec rm -rf {} +

Using find and xargs

The xargs command allows utilities like rm to accept standard input as arguments. This method pipes the output of find to xargs, which then executes the removal command ?

$ find /path/to/search -name "Dir_name_to_delete" -type d -print0 | xargs -0 rm -rf

Command Parameters

-print0    - separates found paths with null characters (handles spaces in names)
|          - pipes output from find to xargs
xargs -0   - reads null-separated input from find
rm -rf     - removes directories recursively and forcefully

Example

To find and remove directories named "cache" using xargs ?

$ find /var -name "cache" -type d -print0 | xargs -0 rm -rf

Comparison

Method Performance Handles Spaces Best For
find -exec Good Yes (with quotes) Simple operations
find | xargs Better Yes (with -print0/-0) Complex operations

Safety Tips

Always test your commands with -ls instead of -exec rm first to see what will be deleted ?

$ find /path/to/search -name "temp" -type d -ls

Conclusion

Both methods effectively find and remove directories recursively. Use find -exec for simple operations and find | xargs for better performance with many directories. Always test with -ls before actual deletion to avoid accidental data loss.

Updated on: 2026-03-15T17:26:00+05:30

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements