How to Delete Files and Directories in Linux [rm command]

Managing files and directories is one of the most crucial tasks in Linux; cleaning up old files helps you organize your workspace and free up storage space for newer file operations. But how do you delete files and directories in Linux? There are a couple of ways to do this, for instance, using the basic commands like rm and rmdir that help you delete a file or directory or using flags with the remove command for interactive or forceful deletion.

By the end of this guide, you will be able to easily delete files and directories in Linux. With the advanced commands, we will also look at how we can delete single and multiple files, force delete files, or delete files with the same extensions; that’s much more organized.

So, let’s get started without taking much of time.

Also Read: How To Zip A Folder In Linux Using Compression Levels

How to Delete Files in Linux

As mentioned in the introduction, there are a couple of ways to delete files and directories in Linux. One of the most common methods is the “rm” command, which can be used to delete individual and multiple files, directories, and more. In this guide, we will be using the “rm” command for all the operations. But how can one command be used for multiple operations? By the use of flags.

1. Deleting Files using the “rm” Command

To delete a single file, you simply use the rm command followed by the name of the file. Here’s an example:

rm filename.txt

In this case, the file named filename.txt will be removed from the current directory. Make sure you are in the same directory where the file exists, or provide the full path to the file.

You can use the “cd” command to change the directory and then use the command to delete the command. Here, change the filename.txt with the exact name of the file with the extension.

Also Read: How to Check Linux Version | Kernel & Distribution


2. Deleting Multiple Files

What if you need to delete more than one file at a time?

That’s easy with rm. Just list the files you want to delete, separated by spaces. Something like this,

rm file1.txt file2.txt file3.txt

This command will delete files 1, 2, and 3. The command is similar to the basic rm command to delete the files; however, it makes it easier to delete files without having to use the rm command repeatedly to delete individual files. 

In addition, this command doesn’t require you to have files of the same kind; here, file 1 can be a text file, file 2 is an image file, and file 3 is a different file, like a PDF file. Irrespective of order and kind, however, they are present in the same directory.


3. Using Wildcards for Batch Deletion

If you want to delete multiple files that share a similar name or extension, you can use wildcards. Now, this command is helpful when you want to delete all files that end with the same extension rather than listing them in the command for deleting multiple files, as seen before.

For example, to delete all .txt files in a directory, use:

rm *.txt

The asterisk (*) acts as a wildcard, matching all files with the .txt extension. 

Now, be careful with wildcards; if you are in the wrong directory, you might end up losing other important files unknowingly. Also, sometimes, you might have a file that you didn’t wish to delete, but due to the use of the wildcard, it’s deleted, too.

Also Read: How to Start, Stop, and Restart Apache Ubuntu?


How to Delete Directories in Linux

Deleting directories in Linux can be slightly different from deleting files, as directories can either be empty, contain files, or have subdirectories in them. Now, there are two commands to make this happen: rm and rmdir, but each has specific use cases.

Let’s look at some of these use cases,

1. How to Delete an Empty Directory

If the directory is empty, the simplest way to delete it is by using the rmdir command. 

Here is how it works,

rmdir directory_name

This command removes the specified empty directory. If the directory contains any files or subdirectories, the command will fail, prompting you to clear the contents first. Thankfully, safe.

Also Read: How to Rename Files and Directories in Linux?


2. Deleting a Directory and its Contents

For directories that contain files or subdirectories, the rm command with a flag (-r) can come in handy. This command is a go-to option and allows you to delete a directory with files or subdirectories in it. Now, this command will work when the 1st command fails, as the directory has files in it.

rm -r directory_name

This command will delete the directory along with everything inside it: files, subdirectories, and all. However, it is a powerful command and needs to be used with caution.


3. Force Deleting Directories

Most times, there are directories or files that cannot be deleted due to permission issues or other restrictions. Here, you can use a flag along with the rm command to force delete directories on Linux. The (-f) flag can be used with the (-r) flag to forcefully delete Linux directories.

rm -rf directory_name

This command is risky, as this combination forces the removal of the directory and its contents without any prompts. Always be cautious and double-check the directory name before executing the command to avoid accidental deletion.

Also Read: How to Download & Install VirtualBox in Ubuntu?


Using Flags and Options with the “rm” Command

The “rm” command in Linux can feel a little overwhelming; it deletes multiple files or files with the same extensions (wildcard) or just a delete. But what if you want to confirm each file before deletion while deleting multiple files? Or do you want to track what files are deleted and the deletion progress? This is where the flags come into the picture. 

The flags modify how the command behaves, allowing you to customize the deletion process for your specific needs. In this section, let’s look at some of the basic but most useful flags.

1. Interactive Mode

The interactive mode prompts you to confirm each file or directory before it’s deleted. This is a great option when you are unsure what files are being removed or are available in the working directory. That’s pretty handy.

To use the interactive mode, use the “-i” flag along with the rm command. Here is what your command should look like:

rm -i file1.txt

In response to this command, the terminal will offer the following output,

rm: remove regular file 'file1.txt'? y

Let’s understand the output. Here, the terminal is asking if you wish to remove the file1.txt, which is a regular file and doesn’t require any additional permissions. “y” (Yes) is a keyboard input to confirm the deletion, and you can cancel the deleting by using “n” (No) in place of “y.”

Also Read: The Best Free Screen Recorders for Linux/Ubuntu


2. Force Deletion

The second flag, which is one of the most useful with the “rm” command, is the force deletion flag. This flag forces the removal of files and directories, even if there are permission issues or the files are write-protected. It helps in bypassing prompts and ensuring the file is deleted without any interruption.

To use the force deletion flag, append the flag “-f” after the “rm” command. Here is what your command should look like:

rm -f file1.txt

In this case, even if file1.txt requires additional permission to be deleted, it can be forcefully deleted using the “-f” flag. Be cautious; using the rm command in combination with -f and -r flags can delete a lot of important data without any warning.


3. Recursive Deletion

The -r flag is used to delete directories and all their contents, and we have also used this flag in our previous section while learning how to delete directories using the rm command. Now, let us quickly understand why “-r” is a crucial flag for deleting directories.

When you use a direct command such as “rmdir directory_name” while having contents such as files and subdirectories under it, you will see an error, as the directory has contents in it. So, to use the command directory, you will first have to delete all the files inside the directory, empty it, and then delete it. A lot of work, right?

But with the use of “-r” (recursive flag) in combination with the “rm” command, you delete all the subdirectories and files and the directory itself in one shot. No more extra work.

Here is what your command will look like,

rm -r directory_name

Now, the directory, directory_name, with all its content, will be deleted. Be cautious while using this flag, as you might not want to delete a certain file or subdirectory.

Also Read: Want to Change Your Linux User Password? Here is the Guide For You


4. Verbose Mode

The next flag on our list is the verbose mode, which is helpful when you want a detailed output of what the rm command is doing. For instance, if you run an rm command with the wildcard and delete more files and want to see the progress, you could use the verbose mode for this. In short, it is helpful when you want to track the progress of deletions, especially for large directories.

In another example, if you are deleting a directory and want to see which files or subdirectories are currently being deleted, you can use the “-v” flag with the rm and -r commands. 

Here is what the rm command will look like with the “-v” flag,

rm -rv directory_name

For this, you will get an output something similar to the following:

removed 'directory_name/file1.txt' 
removed 'directory_name/file2.txt' 
removed directory: 'directory_name'

That looks great. Doesn’t it?


5. Combining Flags

By now, we have seen four flags in combination with the rm command. And possibly, it helped you with all the questions you had about how to delete files and directories with the rm command. However, there is still one question that requires special attention.

Can you combine these flags together?

Yes, you can combine these flags together and perform complex operations. For example, if you want to delete a non-empty directory forcefully and see detailed output, you can use:

rm -rfv my_directory

This deletes the directory and its contents, skips prompts, and displays the deletion progress.

Now, we have a clear idea of how to use flags with the rm command. Here are a few notes to refer to before using the rf command with the flags:

  • Avoid combining -r and -f unless you are absolutely sure of the directory’s contents.
  • Use the -i flag when deleting important directories to prevent accidental data loss.
  • Always double-check the directory path before running rm -rf.

Also Read: Linux Commands Cheat Sheet | Using Linux Like a Pro


Recovering Accidentally Deleted Files

When using the “rm” command, recovering deleted files can be tricky, and this command permanently deletes data without sending it to a trash bin.

There are a few methods to recover accidentally deleted files. However, they don’t always work based on your system configurations. Here are a few methods.

1. Recovering Files with extundelete

If you’re using the ext2/ext3/ext4 file systems, extundelete can recover files deleted from an unmounted partition. This is the most handy method to recover files if you accidentally delete them using the rm command.

To recover deleted files with extundelete, you can use the following command,

extundelete /dev/sdX --restore-all

Here, you need to replace the /dev/sdk with the path where the files were stored. While this method works, it doesn’t guarantee results all the time. So, let’s not be too hopeful.


2. Using testdisk for File Recovery

testdisk is a third-party tool that you can readily install on your Linux system using the apt command. This recovery tool helps in retrieving lost partitions and files. However, the results are not always guaranteed, and you may also recover partial files.

To install testdisk, you can run this simple command in your Linux terminal,

sudo apt install testdisk

This command will install the testdisk tool, and users can then follow on-screen instructions to recover their data.

Also Read: How to Create Your Own VPN Server Using Raspberry Pi


Frequently Asked Questions [FAQs]

Can files deleted with rm be recovered?

Files deleted with rm are typically unrecoverable as they bypass the Trash. However, recovery tools like extundelete or testdisk may retrieve them if no data overwrite has occurred.

How can I delete directories with unusual names?

Directories with spaces or special characters can be deleted by enclosing the name in quotes or escaping the characters with a backslash.

Is there a way to confirm files before deletion?

Yes, adding the -i flag to the rm command prompts for confirmation before each file is deleted, making it safer for crucial deletions.

What makes rm -rf dangerous?

The rm -rf command deletes directories and their contents without confirmation, which can lead to accidental loss of important data if used carelessly.

Are files permanently removed after deletion?

Deleted files remain on the disk until overwritten. Secure deletion tools like shred ensure they cannot be recovered.

How can I prevent accidental deletions?

Preview files with ls or find, use interactive deletion flags, and back up important data before deletion to avoid mistakes.

Before You Leave

Get Our Prime Content Delivered to your Inbox for Free!! Join the Ever-Growing Community… Right Now.

Give this article a quick share,

Wrapping up: How to Delete Files and Directories in Linux [rm Command]

Deleting files and directories is a simple yet powerful task; however, it also requires attention and caution. From basic deletions using the rm command to advanced options to recover deleted files, we tried to cover the most for you.

However, the rm command is not the only deletion command; you can also use the “unlink” command. Or you can use the rm command in combination with findrsync, or shred in combination with the rm command for more advanced operations. 

Always remember the need for caution, double-check paths, use interactive modes, and follow the basic rules to avoid accidentally deleting crucial files. 

If you like what you read, give us a quick share on your social media platform and give us all the love and support. You can also connect with us on our Telegram ChannelFacebook PageReddit Community, and X to never miss out on tech updates.

Leave a Reply

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

Previous Post
Streamlabs OBS

How to Live Stream Games using Streamlabs OBS?

Next Post
Kali Linux Distro

How to Check Linux Version | Kernel & Distribution

Related Posts
Total
0
Share