Remove directories recursively in linux

How do I remove a directory and all its contents?

The following command will do it for you. Use caution though if this isn’t your intention as this also removes files in the directory and subdirectories.

«-f» is «—force» which overrides some sanity checks and prompting. A safer command to start with would be rm -r directoryname .

@JimParis I think the word «safer» is relative. Suppose you are writing a script to run on a remote computer. That script has a command which is supposed to remove a directory. Here, it would be «safer» to use rm -rf directoryname coz you wouldn’t want your script to pause execution, because it’s waiting for user input. Of course, you have to be sure that deleting the directory would do no harm.

if rm -rf directoryname fails you, try using rm -R -f directoryname , or rm —recursive -f directoryname .

If you are not having any luck with these, you should consider reinstalling rm or switching shells.

These were the options available on my rm man page, I looked it up by typing man rm to view my options on recursive deletion and the force options.

Does your rm man page list -r ? What does it do? (Try it in a directory that you create just for testing purposes, with only dummy files (and maybe subdirectories) in it.) What operating system are you using?

P.S. If rm -r doesn’t work, that would be an OS issue, not a shell issue. (Strictly speaking, it would be an issue with the version of rm that you’re using, so you could address it by installing a different version of rm , or searching your system to see whether you already have a different version of rm in some directory other than /bin .)

Ah, right. I forgot to mention I’m on Ubuntu 14.04 When I ran man rm in my terminal, it gave me a text file with the less text viewer. I scrolled found an indented entry with a whole that had the -R and —recursive options cozied up with the -r option, signifying that all of those arguments are identical.

edit: have you tried sudo rm -r directoryName ? The unwritten rules of the basic commands is that -r will allow a program to run recursively on every file your filesystem (starting where ever you choose!) and that -f will forcefully do things, even if it’s dangerous. ‘cd’, ‘mv’, ‘ls’ mostly holds this principle true. ls -r / is gonna be a duzie, and cp -rf / /dev/null will destroy everything on your filesystem.

Читайте также:  Installing linux on my macbook

Other answers show how to completely remove a directory’s content, but IMO they don’t address the literal question of the original post — that is, how can one delete subdirectories (as opposed to usual files). In other words, how can one delete empty directory structures while keeping subdirectories containing files ?

This can be achieved with find :

find directoryname -type d -delete 

This command will recursively search for directories ( -type d ) through directoryname and -delete them only if their subdirectories or themselves don’t contain any files.

Источник

How To Remove Files or Directories Recursively in Linux

Sue Wayne

No worries. Wondershare Recoverit can get back your lost files within 3 steps. The ultimate and professional Linux data recovery software is totally reliable and 100% safe.

A directory can have many subdirectories and files within it. Removing all files and subdirectories in a directory may be necessary when working with the Linux filesystem. It is referred to as recursive deletion. Use the rm command to recursively remove files or directories (also known as folders in Windows) in Linux. The rmdir command only removes empty directories. This guide will present the steps to recursively remove files and directories in Linux.

In this article

Part 1. How To Remove Directory Recursively in Linux Using rm Command

A summary of the rm command syntax for removing directories/folders recursively:

Command Syntax
Description

In Linux and Unix-like systems, everything is considered a file. In other words, «files» include photos, documents, directories/folders, SSD/hard drives, NIC, USB devices, keyboards, printers, and network communications.

Examples Of How To Delete A Folder Recursively

In this example, we will delete the data folder in the current home directory recursively:

Before removing the data directory, the specified /home/vivek/data/ directory will be emptied of all subdirectories, including their subdirectories and files. Unless the -f (force) option is specified on the command line, the user is prompted to remove any write-protected files in the directories:

Alternatively, you can use the command that follows:

To remove a folder whose name begins with a “ — ,” such as “ -dsaatia ,” use one of the following commands:

You can also run the following command:

To see verbose outputs, we can use the -v option. In other words, the rm command on Linux will explain what happens to our files and folders. As an example:

rm -rfv /path/to/dir1
rm -r -f -v /home/vivek/oldpartpics

Delete Folders With Unique Name Characters

Your folders and files may contain while spaces, semicolons, backslashes, and other characters in Linux. As an example:

Assume we have a folder called «Our Sales Data» and » baddir# » or » dir2 ;# » in it. So, how do we get rid of those directories with unusual names? The solution is straightforward. We will enclose the problematic filename or folder name in quotation marks. As an example:

rm ‘Our Sales Data’
rm -rfv ‘/path/to/Dir 1 ;’
rm -r -f -v «baddir#»
rm a\ long \dir1 \name

Sometimes a backslash ( \ ) is required before the meta-character in your filename or folder name:

remove a directory or folder recursively

Part 2. How To Delete Files Recursively in Linux Using rm Command

Delete All Files Recursively

When used with the -r flag, the rm command will remove the contents of all types of files.

Читайте также:  Захват сетевого трафика linux

But first, using the ls command, let’s look at the home directories. In this example, there are five directories: Desktop, dir2, Documents, Downloads, and removerecurdir.

use the ls command

Assume we want to delete the removecurdir and its contents, including all files and subdirectories. Run the syntax below.

The ls output shows the directory and its contents were successfully removed.

delete files recursively in linux

Remove Files by Size Recursively

Here are the steps to recursively delete files (

The find syntax is as follows:

You can use sudo to access the protected files in the example below.

sudo find /var/log -type f -size -10M -exec rm <> +

The minus sign ( — ) must be replaced with a plus sign ( + ).

In the following example, I will use the previous syntax to remove files larger than 1 GB.

find /var/log -type f -size +1G -exec rm <> +

Remove Files by Extension Recursively (File type)

The following section describes how to delete files recursively by extension or file type.

Look for the content of the home directory, which is called testhint with the tree command.

The parent directory testhint has a file (file1.txt) and two subdirectories: testhint2 has file3.txt, and testhint3 has file3 and something.txt.

parent directory testhint

Assume you want to remove all txt files recursively. The syntax is as follows:

Then, run this command to remove all text files recursively within the parent directory testhint.

find ~/testhint -type f -name ‘*.txt’ -print -delete

All text files were deleted, leaving only file3 without an extension.

remove all txt files recursively

You can also delete files by extension by the find together with exec commands.

find together with exec commands

The syntax for removing files by extension with -exec is as follows:

Run the command below to remove the .log files.

find ~/testhint -type f -name ‘*.log’ -exec rm -f <> \;

The xargs command provides a similar solution. The distinction between xargs and exec is that exec executes the rm function whenever a file matches the condition. The command xargs run the rm command once for each file found that matches the condition.

To remove all files by extension using find and xargs , use the following syntax:

remove extension using find and xargs

Enter the command shown below to remove all .c files with xargs.

find . -name «*.c» -print0 | xargs -0 rm

Once again, the selected extension files were successfully deleted.

successfully deleted selected extension files

Recursively Deleting All Files Based On Permissions

Let’s take a look at the new content in the testhint directory. Four files have full access (file2, file3.c, file6.c, and file7).

content in the testhint directory

Assume you want to locate and delete all files with full permissions for everyone. The syntax is as follows:

Run the command below to remove all files with full access for all users.

find ~/testhint -perm 777 -print0 | xargs -0 rm

remove all files based on permissions

Delete Files Recursively Based on Their Modification Or Creation Time

Execute the syntax that follows:

find ~/testhint -perm 777 -print0 | xargs -0 rm

If you want to delete files created or modified on the last day (last 24 hours), use the following command, where 1 denotes the number of days, and the minus ( — ) symbol denotes files created or modified before the defined number of days.

find -type f -mtime -1 -delete

Replace the minus symbol with a plus symbol to remove files created or modified before a day, before 24 hours.

Читайте также:  Linux выполнять команду каждые 10 секунд

find -type f -mtime +1 -delete

Part 3. What To Do If You’ve Accidentally Deleted a File or Folder in Linux?

In Linux, unintentionally deleting a file or folder can be a real hassle, but there are actions you can take to improve your chances of successful recovery:

  • Stop using the computer: To prevent further data loss, stop using the computer immediately and avoid writing any new data to the disk where the deleted file was located.
  • Act quickly: The longer you wait to start the recovery process, the greater the risk of permanent data loss.
  • Create backups regularly: Regular backups can ensure that you have a recent copy of your important data in case of accidental deletion.
  • Keep your file system in good condition: Regular disk maintenance, such as checking for errors and fixing them, can help keep your file system in good condition and make recovery easier.

The best Linux data recovery tools can also help you recover lost or deleted files. Following these tips and using the correct data recovery tool can increase your chances of successfully recovering your deleted files and folders in Linux.

Источник

How to Search and Remove Directories Recursively on Linux

In one of our previous articles, we explained how to find out top directories and files consuming the most disk space on file system in Linux. If you notice that such directories no longer contain important files and subdirectories (such as old backups, downloads etc..), then you can delete them to free up space on your disk.

This short tutorial describes how to find and delete directories recursively in the Linux file system.

To achieve the above purpose, you can employ the find command together with rm command using the syntax below. Here, the + sign at the end enables multiple directories to be read simultaneously.

$ find /start/search/from/this/dir -name "dirname-to-delete" -type d -exec /bin/rm -rf <> +

Attention: You must use rm command carefully because it is one of the most dangerous commands to use in Linux: you may accidentally delete critical system directories, thus resulting to system failure.

In the example below, we will search for a directory called files_2008 and delete it recursively:

$ $find ~/Downloads/software -name "files_2008" -type d -exec /bin/rm -rf <> +

You can also use find and xargs; in the following syntax, -print0 action enables printing of the full directory path on the standard output, followed by a null character:

$ find /start/search/from/this/dir -name "dirname-to-delete" -type d -print0 | xargs -0 /bin/rm -rf "<>"

Using the same example above, we have:

$ find ~/Downloads/software -name "files_2008" -type d -print0 | xargs -0 /bin/rm -rf "<>"

Last but not least, if you are concerned about the security of your data, then you may want to learn 3 ways of permanently and securely deleting ‘Files and Directories’ in Linux.

Do not forget to read more useful articles about file and directory management in Linux:

In this article, we showed you how to find and remove directories recursively on Linux. If you have any question or extra ideas you want to add to this topic, use the comment section below.

Источник

Оцените статью
Adblock
detector