How to find and delete directory recursively on Linux or Unix-like system

How to find and delete directory recursively on Linux or Unix-like system

To find and delete a directory recursively on a Linux or Unix-like system, you can use the find command with the -type d and -delete options. The syntax is as follows:

find /path/to/search -type d -name directory-name -delete
Source‮‬:www.lautturi.com

Replace /path/to/search with the path of the directory you want to search, and directory-name with the name of the directory you want to delete.

For example, to find and delete a directory called temp in the /home directory, you would run the following command:

find /home -type d -name temp -delete

This will search the /home directory and all of its subdirectories for a directory called temp, and delete it and all of its contents.

Keep in mind that the find command will search recursively, so it may take a while to complete if you are searching a large directory tree. You can use the -maxdepth option to limit the depth of the search. For example, to search only the top-level directories in the /home directory, you would run the following command:

find /home -maxdepth 1 -type d -name temp -delete

This will search only the top-level directories in the /home directory for a directory called temp, and delete it and all of its contents.

It is important to be careful when using the find command with the -delete option, as it can delete a large number of files and directories quickly and irreversibly. You may want to use the -print option first to see what will be deleted before using the -delete option.

find /path/to/search -type d -name directory-name -print

This will search the specified directory and print the paths of the found directories, but it will not delete them. You can then review the list of directories to be deleted and make sure it is what you intended before using the -delete option.

Created Time:2017-10-16 14:38:46  Author:lautturi