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 it. One hurdle in deleting the files is to do a recursive deleting because by default Unix systems do not allow deleting of a directory if it is not empty. So in this article we will see how to find and remove directories recursively.

Using find and exec

The below command first searches for the required directory using the find command then executes the ‘rm’ command to recursively remove the directory using the recursive option as well as the force option. The various parameters used in the command are explained below this command.

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

The meaning of these arguments is below.

-type d - restricts the search only to directories
-exec - executes an external command, in this case it is rm –r
{} + - appends the found files to the end of the rm command

Using find and xargs

The xargs allows commands like rm and mkdir to accept standard input as argument. So in this case we first use find command to find the required directory, then act on that directory by supplying it as an argument to the xargs command. The print0 option allows full directory path which becomes available to the xrags command. Then we apply the rm command in a similar way as we did in exec command above.

$find /path/to/search -name " Dir name to be deleted " -type d -print0 | xargs -0 /bin/rm -rf "{}"

Updated on: 03-Jan-2020


Kickstart Your Career

Get certified by completing the course

Get Started