Delete file on Linux, learn how to avoid mistake when you are deleting files

Delete a File Linux – Secrets that you didn’t know about it [Complete Guide]

Delete a File Linux: This article will explain how to delete files in terminal using the rm, unlink, and rmdir commands to delete files and directories in Linux. Those commands are critical and you should use them carefully.

On Linux, the rmdir and rm functionality are to delete directories and files, like any Unix-based operating system, including macOS.

They’re comparable to the commands del and deltree commands in Windows and DOS. These commands are mighty and have quite a few parameters.

It is essential to note that files and directories deleted using rm and rmdir are not transferred to the Trash. They are instantly excluded from your computer. If you unintentionally delete files applying these commands, the only method you’ll be capable of restoring them is from a backup.

However, you will see that we could create our own solution, to create trash and send the deleted files to there.

Besides learning how to use the commands rm, rmdir, and unlink, you will learn:

  • Find and Delete old files, for example, files that you didn’t access more than 30 days ago.
  • How to decrease the risk of deleting a wrong file and how to recover them.
  • How to use an alias to prevent mistakes with the rm command.
  • We will show how to delete safetly the sensitive files.

What is rm command?

The rm means “remove,” so this command allows us to delete a file Linux. Also, this command is available on any Unix-based system, including the Mac OS.

How to delete a file in Linux?

First, let’s see how to remove files with rm:

The most straightforward example is deleting a single file in the current directory. Let me show you an example:

rm bitslovers-post-delete-files-on-linux.txt

But, If the file is not in the current working directory, you can type the full path from that file, for example:

rm /tmp/bitslovers-post-delete-files-on-linux.txt

Deleting multiple files in Linux

We can pass more than one file to the rm command to delete all files at once. Let’s see how easy it is:

rm how-delete-files-on-linux.txt complete-guide.txt

Delete files with specific extension Linux

But, sometimes, we have a list with several files, and we don’t want to specify all of them on the command. So, instead, we can use Wildcards to filter a collection of files that we want to delete.

For example, we can use the filename to have a clear pattern on their names or extensions. Let’ see a sample?

Suppose that you are on your home directory, with some photos in the Pictures folder that you don’t want anymore. And you noticed that all files have the extension .jpeg. So, to delete them at once:

rm *.jpeg

Easy, right? You also can do it:

rm ~/Pictures/*.png

In some scenarios, a file is write-protected; in these cases, you have to answer a prompt before deleting the file. You must reply with y or n and hit “Enter.”

Attention: Use Wildcards is very dangerous if you are unaware of any crucial files on the directory when executing the rm command. To decrease the risk, you can use the -i (interactive) option. However, using that option requires you to approve the deletion of each file.

So, How delete file in Linux with prompt?

Like we saw above, you can use the -i (interactive) option, like this example:

rm -i *.txt

How to remove files in Linux without prompt

Like we saw before, you need to confirm before the rm command deletes write-protected files. To delete directories that contain several sub-directories and files and suppress these confirmation messages, use the -r (recursive) and -f options.

How to force delete a file on Linux?

The -f (that means force) option is the opposite of interactive. So, It does not prompt for verification regardless if files are write-protected.

rm -rf directory


rm -rf *.txt

Caution is needed here. If you use the rm -rf command and by mistake delete a file or folder from the system, it could cause data loss or system failure. It’s risky, and attention is the best strategy. 

If you’re afraid of removing files, you should substitute your rm command with a different one that asks you for confirmation before permanently removing files. You can use an alias for this goal:

Create alias for rm command

alias rm="rm -i"

Add this command above on your ~/.bashrc, so you will not lose the alias when you restart your computer. And, every time that you execute rm, the prompt for confirmation will be shown for you.

Delete a File Linux: How to restrict rm command in Linux

Also, there is an excellent tool to prevent accidental deletion of important files: safe-rm

Safe-rm is a security tool designed to interrupt the unintentional deletion of critical files by replacing /bin/rm with a wrapper version, which examines the presented arguments against a configurable blocklist of files and directories that you should never remove.

Users who try to delete one of these protected files or directories from the block list will not be able to delete so and will be displayed a notification message alternately.

If you don’t have a clear view of which directories you have, you can understand the directory structure and the files that the rm will delete when you use it with options -rf, use the tree command.

The rm command also provides the options –one-file-system, –no-preserve-root, and –preserve-root, but those are only suggested for advanced users. If you get something wrong, you could unintentionally delete all your system files. Look at the command’s manual page for further information.

How to install tree command in Linux?

You can use apt-get to install this package onto your system using Ubuntu or different Debian-based distribution. On other Linux distributions, utilize your Linux distribution’s package command tool instead.

sudo apt-get install tree

Running the tree command gives a simple picture of the directory structure and files under the directory from which it is run.

You can also provide a path to the tree command to start the tree from different directories in the file system.

tree /tmp/blog
How to use tree command on Linux. Use that command before delete a folder, to check if you really should do it.

Delete only files in a directory on Linux

For example, let’s suppose that you have a folder with several files and subdirectories. And you would like to delete only files from the first level.

You can utilize the find command with -type f for files only and -maxdepth 1, so find won’t seek files in sub-directories of /path/to/directory and rm -i will prompt you on each delete so you can confirm or deny the delete as we saw before. The -v option on the rm command shows a message for each file that was deleted.

find /home/user/Download -maxdepth 1 -type f -exec rm -iv {} \;


find /home/user/Download -maxdepth 1 -type f -delete

Although this won’t prompt you for confirmation or output what it just deleted, consequently, most experts run it without the -delete action first to make sure that the files are correct.

However, if you would like to delete all content from the directory and not the directory itself:

rm -rf /path/to/directory/*

This command above will delete all files and subdirectories inside of the /path/to/directory.

Delete files using find command

Remove multiple files Linux using a native command like find, requires also apply the grep and xargs, but it’s very straightforward, let show you how easy it is:

Example: Suppose that you need to delete all your collection of wallpaper from the home directory, and you know that all files are with extensions .jpg and the files name contains the word “wallpaper.” So, to find, filter, and delete the files on a single line:

See this example, delete files with find:

find /home/user -name "*.jpg" | grep -i "wallpaper" | xargs rm

In my opinion, xargs and find command on Linux are the most helpful command ever! You can resolve any complex problem very efficiently.

If you would like to learn more about how delete files with find, check our post: find command with examples.

Also, I recommend reading our Complete Guide about xargs with examples. And discover everything that you can do with Xargs.

How to remove a directory in Linux

We will learn two commands that allow us to remove directories: the rm and rmdir.

How to Remove Directories with rm

You will see that deleting directories that are empty and not empty could be handled differently.

To delete an empty directory, apply the -d (means directory) option. Also, you can utilize wildcards (* and ?) in directory names precisely as you can with files.

For example, if you would like to delete your Download directory (it should be empty).

rm -d /tmp/Downloads

Like files, providing more than one directory name deletes all of the specified empty directories.

See this example:

rm -d /tmp/logs /tmp/Downloads /tmp/backups

Another example is to delete directories that are NOT empty and use the -r (means recursive) option. So, this deletes the directories, and all files and sub-directories included within them.

For example: 

How to delete the download directory?

rm -r ~/Downloads

But, the command above deletes the Downloads directory itself. So, to remove only files and sub-directories from that folder, as we saw before:

rm -r ~/Downloads/*


Use the temporary folder /tmp to store the download files that you are sure you will not need later. Because, when you restart your computer, all files and directories inside the /tmp will be deleted automatically. So, you don’t need to worry about cleaning up files that you use at once. Nowadays, with high-speed internet, it doesn’t make sense to store every file on our computer. 

Also, you can configure your web browser to use the /tmp as the default Download folder, so you don’t need to select the folder for each download.

How to Remove Directories with rmdir

Delete a File Linux: What is rmdir in Linux?

The rmdir command allows you to delete directories too. 

You may be asking yourself, why a second command to delete directories? 

Let me explain:

The rmdir command can only delete empty directories. So, it means that It will never delete files. It could be more secure in some scenarios.

The most simplistic case is deleting a single empty directory. As with rm, you can provide various directories names to the command rmdir or the full path to a directory.

Delete just one directory in the current directory by giving its name to rmdir :

rmdir temp-directory

Delete various directories by giving a list of names to rmdir :

rmdir folder1 folder2 folder3

If you need to delete a directory not in the current directory by defining the full path to that directory:

rmdir ~/Downloads

if you got an error message like this one:

rmdir: failed to remove '/home/bitslovers/Downloads/': Directory not empty

Because you try to delete a not empty folder, rmdir will present you with this error message. In the following sample, rmdir successfully and quietly deletes the directory but declines to delete the projects directory because it contains files. Thus, the project’s directory is left exactly as it was, and its files are untouched.

When rmdir shows a “Directory not empty” error, it stops processing the directories that were passed to it on the command line. So, for example, if you’ve asked it to delete two folders and the first one had files in it, rmdir would show you the error message and do nothing more. You can apply it to overlook these errors with the –ignore-fail-on-non-empty option to process other directories.

Le’s see in the following example, two folders have been given to rmdir. These are directory-A and directory-B. The –ignore-fail-on-non-empty option has been introduced in the command. The directory-A folder has files in it, so rmdir cannot delete it. The –ignore-fail-on-non-empty option forces rmdir to overlook the error and move on to the following folder it needs to process: directory-B, which is an empty folder, and rmdir deletes it.

The command that covers this scenario:

rmdir --ignore-fail-on-non-empty work/reports /work/quotes

To make your life easier, you can create an alias on your ~/.bashrc that automatically adds the –ignore-fail-on-non-empty, so you don’t need to type it every time. For example:

alias rmdir="rmdir --ignore-fail-on-non-empty"

You can apply the -p (parents) option to delete a directory and delete its parent directories. This method works because rmdir begins with the target directory and then back-steps to the parent. Therefore, that directory should now be empty so that it can be deleted by rmdir, and the process reoccurs, stepping back up the path that was given to the command rmdir.

Let me show you the command that is given to rmdir is:

rmdir -p bitslovers/posts

Both the bitslovers and the posts directories will be deleted, as requested.

Linux provides manageable and robust commands for you to delete directories and files right from the terminal command line whether you’re using bash or any other shell. Some people prefer to work with terminal. Others may have no alternative in the matter. They may be running on servers without a GUI placed or on a remote session onto a headless system, for example, a Raspberry Pi device. These commands are excellent for that group of people.

Delete a File Linux: When should you use the rmdir?

When you get started on Linux, I recommend using rmdir for the scenarios where you don’t know if you have files in the directory you want to delete. For example, if you believe that the directory is empty, always use rmdir. Otherwise, if the directory has files and you forget about them, you will be protected against the mistake of deleting files that you don’t want.


Never run rm -rf / 

Caution! These samples will delete all files on your computer if execute it.

$ rm -rf /
$ rm -rf *

The command rm -rf (any of these, rm -rf /, rm -rf *, and others) is often used in jokes and incidents about Unix disasters. The rm -rf /, if run using the root user, would affect the contents of all files that are writable and mounted on the filesystem in the computer to be deleted. Do not execute these commands. 

Unlink command in Linux

The unlink command doesn’t get as much awareness as other GNU Core Utilities, like the rm command. However, it has a straightforward function to remove a file or symbolic link. Let’s see some of the differences between unlink and the rm command.

Unlink vs. rm command

The unlink command contrasts in many ways from the rm command. Behind the scenes, it uses the related unlink() system call. However, there are practical distinctions that users will notice.

rm Command:

  • Capable of deleting many files at once
  • Does security checks (it shows prompts if no write permissions is the case)
  • Can give feedback via STDOUT
  • Enables us to delete directories

unlink command:

  • does not check and prompt for confirmation, it means that it is less secure.
  • Cannot delete more than one file at once
  • It’s not possible to delete directories
  • It does not give extra options.

Unlink command in Linux with examples

The unlink command goal is to remove a single file only, is not allowed to passing more than one file name like the rm command. It has no extra arguments options, only the –help and –version. The syntax is simplistic, use the command and pass a single filename, for example:

unlink /tmp/my-notes.txt

If we use a wildcard to unlink, you will get an extra operand error, and the reason for that is because the wildcard denotes more than one file.

Let’s one example:

unlink /tmp/*.txt

You will see an error message like this one:

unlink: extra operand "my-notes.txt" 

Try ‘unlink –help’ for more information.

Delete a File Linux: How to undo rm in Linux

I have bad and good news for you: it’s not possible to undo the rm command. However, let me explain the bad one first and why. Later I will present a solution for it:

Where do files go when the rm command is executed?

Nowhere, gone, disappeared. Well, more accurately, the file becomes unlinked. The files are still sitting there on the disk, but the link to it is removed. So it’s possible to recover the files, but the metadata is lost now, and nothing’s recoverable. That’s is the reason that we can’t undo the rm operations. Some software tries to recover files but not necessarily will, and it’s not a straightforward process. It demands time.

Let’s see another reason:

There is no Trash can when you execute the rm command, nor should there be. If you necessitate a Trash can, you should use an interface. There is a command utility in trash-cli for Ubuntu, but most of the time, the GUI file browsers like Nautilus or Dolphin already provide a standard Trash can. So, for example, files deleted in Dolphin will be visible in the Trash from Nautilus.

Deleted files are usually located somewhere like ~/.local/share/Trash/files/ when trashed. The rm command on UNIX/Linux is equivalent to del on DOS/Windows, which also deletes and does not move files to the Recycle Bin. Also, I would like to highlight that moving a file across filesystems like a USB disk from your hard disk drive involves two operations: 

First, a new copy of the file is done. And, second, unlinking the original file from your hard disk. You wouldn’t desire your Trash to have with these extra copies.

Now let’s see the good news? 

It’s incredible how Linux provides us the ability to customize our system and our daily tasks. When you face a limitation on the usability of Linux, you need to stop for seconds and realize that maybe it is not a limitation.

Sometimes we do not note that some limitations were designed to provide a generic structure on the system that allows us to build our solution and highly customization. For example, the fact that we don’t have Trash to move your files when you execute the rm command doesn’t mean you have accepted that reality. However, we can build one solution that can handle that! 

Great, right? But, how? Let me show you.

One of the first ideas that come to my mind was creating an alias that can override the rm command by moving instead of deleting the files right the way. However, the alias command doesn’t allow us to provide arguments.

So, how to resolve that? Let’s see:

Delete a File Linux: How to prevent a mistake with the rm command?

The most simplistic way is to create a function called “rm” that will override the original rm command on your ~/.bashrc. Let’s how to do it:

 mkdir -p /tmp/trash
 mv $@ /tmp/trash

With this new rm above, you will be able to recover files in Linux after you have executed rm.

Easy, right? Add those lines above at the end of your file (~/.bashrc).

Note: You will need to type bash on your terminal or open a new terminal to make the changes available to use.

Moving the files to /tmp, it’s the best approach, in my opinion, because all files will be deleted when you shut down your computer. So, you still have time to recover your files if you deleted any files by mistake and don’t need to clean up the files, and this approach will automatically release space when you turn on your computer again. However, you can specify any folder you want. Remember that you need to clean up the folder manually or create a cron job (a utility on Linux to automate tasks according to a schedule you define) that automatically deletes that folder or files for you.

And if you need to clean up the oldest files that you didn’t access within 30 days or more:

find . -name "*.log" -atime +30 -delete

You can execute the command above to remove the old files from your trash folder automatically.

Delete a File Linux: Securely remove files in Linux

We have learned that when you delete files using the command line, the operating system unlinks the files from our disk. So they got lost, but behind the scenes, the files were still physically on the disk. Also, it’s possible to use appropriate software to recover them.

For example, this could be a security problem if you decide to sell your computer to another person.

How can we delete the files that could be impossible to recover?

Disk wipe for Linux

A disk wipe may be the best solution if we need to overwrite and delete every individual byte from a computer’s hard disk. The term disk wipe relates to the action of cleaning a computer’s hard disk. The term also points to a class of computer software products created to achieve this task more quickly and efficiently, with some variants of disk wipe software. 

The process is not only easier than reformatting a hard drive; it is also considered by many to be more secure. But, you may be asking yourself, why is it more secure?

Let me explain:

Because it guarantees that all data, including licensed software and files that may hold passwords or other personal information, is overwritten. 

Now, let’s see an example of software that we can use for free that achieve that goal.

Shred for Linux

The shred command allows us to overwrite the specified files repeatedly and make it hard for software to recover the data. The syntax is as follows:

shred [option] <target>

The shred command also overwrites data in a file or a whole device with random bits, making it nearly unachievable to recover. Finally, this command permanently deletes the data. Also, the command has some options which you can use to wipe a disk as:

  • -u eliminates the file after overwriting
  • -n  (iterations=N) overwrites N times rather than the default (3)
  • -s (size=N) defines the number of bytes to shred
  • -u trims and removes files after overwriting
  • -v displays a verbose message regarding the process
  • -f modifies permissions to support writing if needed
  • -z appends a final overwrite with zeros to hide shredding
  • -x does not round file sizes up to the following complete block

So, to wipe the partition, you can apply. 

shred -vfz -n 10 /dev/sda1

Change the /dev/sda1 for your desire disk.

How to install Shred on Ubuntu

The shred it should already be installed on your computer, but if you need to install it, follow the command:

sudo apt-get install coreutils


Delete files and directories are the firsts actions that maybe we do when we get started with Linux, and it’s considered an easy task. However, you have noticed that it could get complicated on specifics scenarios that require attention from us.

So, rm and rmdir delete directory Linux command.

We also learned about the unlink command. I never used that command to delete files daily, but it is good to be aware of all our alternatives. In addition, there are specific scenarios where the unlink could be better and useful for scripts and automation tasks. For example, you could use it to provide more security for the automatic tasks done by Shell Scripts to delete and limit the number of files safely.

Whatever command you like to delete files and directories, these commands lend themselves very well to being added in shell scripts. For example, a cron job triggers a script that can help automate routine housekeeping jobs, such as cleaning undesired log files. Only remember of the potential of these commands, test everything delicately, and always keep an up-to-date backup.

If you already have some experience and acknowledged with Linux, before. I hope that you have learned something new.

Please leave a comment below, and give us feedback. It’s crucial for us.

Also, take some minutes and follow us on social media.

1 thought on “Delete a File Linux – Secrets that you didn’t know about it [Complete Guide]”

Leave a Comment

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

Free PDF with a useful Mind Map that illustrates everything you should know about AWS VPC in a single view.