delete multiple directories in linux

How to Delete Multiple Directories in Linux

rm is the most common Linux command used to delete files & directories in Linux. Sometimes you may need to delete multiple directories in Linux. Here are the steps to delete multiple folders in Linux.


How to Delete Multiple Directories in Linux

The simplest way to delete multiple directories is to run ‘rm -rf’ command on their common parent folder. In this command -r option will recursively delete the subfolders and files of specified folder. The -f option is to forcefully delete files & directories, in case of any objections raised by the system.

For example, let us say you want to delete /home/projects/project1, /home/projects/project2, /home/projects/project3, etc. then you can easily run ‘rm -rf’ command on /home/projects folder.

$ rm -rf /home/projects

The above command will delete everything inside /home/projects folder.

If you have hundreds or thousands of files & directories, rm may not work straightaway due to shell limitations. In such cases, you can use find command to get a list of all files & directories to be deleted and use its exec option to run rm command on them all. Here is an example of the command.

$ find -t f /home/projects -exec rm -rf '{}' \;
$ find /home/projects -exec rm -rf '{}' \;

Find is a very versatile command that allows you to find multiple files & directories from different locations, and use exec option to delete them, using a single command.

Here is an example to find and delete all .pdf files from dir1, dir2, dir3 folders.

$ find dir1 dir2 dir3 -name "*.py" -exec rm -rf '{}' \;

Here is a command to find and delete all files from directories dir1, dir2, dir3.

$ find dir1 dir2 dir3 -type f -exec rm -rf '{}' \;

Here is a command to find and delete all directories in folder dir1, dir2, dir3.

$ find dir1 dir2 dir3 -type d -exec rm -rf '{}' \;

Similarly, there are tons of different ways to find and delete multiple files & directories using a combination of find and rm commands.

Also read:

How to Force CP Command To Overwrite Without Confirmation
How to Force Delete Directory in Linux
How to Upload File Asynchronously in JavaScript
How to Store Data in Local Storage in JavaScript
How to Display Local Storage Data in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *