Delete a File Linux - Secrets that you didn't know about it [Complete Guide]
Here is the thing about deleting files on Linux: the commands are simple, but the consequences are permanent. The rm, unlink, and rmdir commands delete files and directories, and they skip the Trash entirely. What is gone is gone.
This works the same on any Unix-based system, including macOS. If you have used DOS or Windows, rm is roughly equivalent to del, and rm -r is like deltree.
I want to be upfront about something: files deleted with rm and rmdir do not go to the Trash. They are removed immediately. If you delete something by accident, your only option is restoring from a backup. Later in this post, I will show you a trick to build your own safety net.
Beyond the basics of rm, rmdir, and unlink, I will also cover:
- Finding and deleting old files (for example, files you have not accessed in over 30 days)
- Reducing the risk of deleting the wrong file
- Using an alias to add a confirmation step to
rm - Securely deleting sensitive files so they cannot be recovered
What is the rm command?
rm stands for “remove.” It deletes files and is available on any Unix-based system, including macOS.
How to delete a file in Linux
The simplest case is deleting a single file in the current directory:
rm bitslovers-post-delete-files-on-linux.txt
If the file is somewhere else, use the full path:
rm /tmp/bitslovers-post-delete-files-on-linux.txt
Deleting multiple files in Linux
You can pass multiple filenames to rm at once:
rm how-delete-files-on-linux.txt complete-guide.txt
Delete files with a specific extension
When you have many files to delete, typing each name is impractical. Wildcards help here. You can match patterns in filenames or extensions.
Say you have a folder full of .jpeg files you no longer want:
rm *.jpeg
Or target a specific directory:
rm ~/Pictures/*.png
If a file is write-protected, rm will ask you to confirm before deleting it. Type y or n and press Enter.
Be careful with wildcards. If you are not sure what files are in the directory, the -i flag adds a confirmation prompt for every file:
rm -i *.txt
How to remove files in Linux without a prompt
By default, rm asks for confirmation on write-protected files. To skip those prompts, use the -f (force) option. Combined with -r (recursive), this deletes directories and everything inside them without asking:
rm -rf directory
Or to force-delete all .txt files:
rm -rf *.txt
This is dangerous territory. A wrong path with rm -rf can wipe out data you did not intend to delete. Be deliberate.
If you want a safety net, you can alias rm so it always asks for confirmation:
Create an alias for the rm command
alias rm="rm -i"
Add this to your ~/.bashrc so it persists across reboots. Every time you run rm, you will get a confirmation prompt.
Restrict the rm command with safe-rm
There is also a tool called safe-rm that prevents accidental deletion of important files. It replaces /bin/rm with a wrapper that checks arguments against a configurable blocklist of protected paths.
If you try to delete a protected file or directory, safe-rm blocks the operation and shows a warning.
If you are not sure what a directory contains before deleting it, the tree command gives you a quick visual layout:
tree /tmp/blog

How to install the tree command
On Ubuntu or Debian-based systems:
sudo apt-get install tree
On other distributions, use your package manager’s equivalent command.
Delete only files in a directory (not subdirectories)
Say you have a folder with files and subdirectories, and you want to delete only the files at the top level. Use find with -type f (files only) and -maxdepth 1 (do not recurse into subdirectories):
find /home/user/Download -maxdepth 1 -type f -exec rm -iv {} \;
Or a shorter version that skips the confirmation:
find /home/user/Download -maxdepth 1 -type f -delete
A word of caution: the -delete flag does not prompt you and produces no output. I usually run the find command without -delete first to verify the results, then add it once I am confident.
If you want to delete everything inside a directory but keep the directory itself:
rm -rf /path/to/directory/*
This removes all files and subdirectories inside /path/to/directory.
Delete files using find with grep and xargs
You can combine find with grep and xargs for more targeted deletions. For example, suppose you want to delete all .jpg wallpaper files that contain “wallpaper” in the filename:
find /home/user -name "*.jpg" | grep -i "wallpaper" | xargs rm
I find find and xargs to be two of the most useful commands on Linux. They handle complex tasks cleanly.
If you want to dig deeper into this topic, check out our Complete Guide about xargs with examples.
How to remove a directory in Linux
Two commands handle directory removal: rm and rmdir.
How to remove directories with rm
Empty and non-empty directories are handled differently.
To delete an empty directory, use the -d option:
rm -d /tmp/Downloads
You can use wildcards with directory names, just like with files. You can also pass multiple directories:
rm -d /tmp/logs /tmp/Downloads /tmp/backups
To delete a directory that is not empty, add the -r (recursive) option. This removes the directory and everything inside it:
rm -r ~/Downloads
Note that this deletes the Downloads directory itself. To remove only the contents and keep the directory:
rm -r ~/Downloads/*
A practical tip: use /tmp for downloads you will not need later. Everything in /tmp is cleared when you reboot. You can even configure your browser to use /tmp as the default download folder.
How to remove directories with rmdir
The rmdir command also deletes directories, but only empty ones. This makes it inherently safer than rm -r because it will never delete files. It just refuses to operate on non-empty directories.
Delete a single empty directory:
rmdir temp-directory
Delete multiple empty directories:
rmdir folder1 folder2 folder3
Delete a directory by its full path:
rmdir ~/Downloads
If the directory is not empty, you get an error:
rmdir: failed to remove '/home/bitslovers/Downloads/': Directory not empty
This is actually a feature, not a bug. The directory and its files remain untouched.
When rmdir encounters a non-empty directory, it stops and does not process the remaining directories either. To skip the error and continue with the rest, use --ignore-fail-on-non-empty:
rmdir --ignore-fail-on-non-empty work/reports /work/quotes
Here, if work/reports has files in it, rmdir skips it and moves on to delete work/quotes (assuming it is empty).
You can create an alias for this in your ~/.bashrc:
alias rmdir="rmdir --ignore-fail-on-non-empty"
The -p (parents) option removes a directory and its parent directories, working from the inside out:
rmdir -p bitslovers/posts
This deletes both posts and bitslovers, as long as both are empty.
When should you use rmdir?
If you are new to Linux, I recommend using rmdir whenever you think a directory is empty. If you are wrong, no harm is done. You get an error message instead of accidentally deleting files you wanted to keep.
A warning: never run rm -rf /
$ rm -rf /
$ rm -rf *
These commands will delete everything on your system if run as root. Modern Linux distributions have --preserve-root enabled by default, which blocks rm -rf /, but rm -rf * from the root directory is still catastrophic. Do not run these commands.
The unlink command in Linux
unlink is less well-known than rm. It removes a single file or symbolic link, and that is it. Let me explain how it differs from rm.
unlink vs. rm
rm:
- Can delete multiple files at once
- Prompts before deleting write-protected files
- Shows output via STDOUT with
-v - Can delete directories with
-r
unlink:
- No confirmation prompts
- Can only delete one file at a time
- Cannot delete directories
- Has no options beyond
--helpand--version
unlink examples
The syntax is simple. Pass a single filename:
unlink /tmp/my-notes.txt
If you try to use a wildcard, you get an error because the wildcard expands to more than one file:
unlink /tmp/*.txt
Output:
unlink: extra operand "my-notes.txt"
Try ‘unlink –help’ for more information.
How to undo rm in Linux
I have bad news and good news. The bad news: you cannot undo rm. The good news: you can build a workaround.
Where do files go when you run rm?
Nowhere. The file’s directory entry is removed, so the operating system no longer knows the file exists. The actual data might still be on the disk, but the metadata that tells the system where to find it is gone. Recovery software sometimes works, but it is slow, not guaranteed, and gets harder the more you use the disk after the deletion.
There is no Trash when you use rm. This is by design. If you want a Trash, you need a tool that provides one. Desktop file managers like Nautilus (GNOME) and Dolphin (KDE) have their own Trash. Files deleted in one show up in the other. The trash-cli utility provides the same functionality from the command line.
Trashed files are typically stored in ~/.local/share/Trash/files/.
The good news: build your own safety net
This is where Linux shines. The system gives you building blocks, and you can combine them into something that fits your workflow.
I wanted an alias that overrides rm to move files instead of deleting them. The problem is that shell aliases cannot accept arguments. But shell functions can.
How to prevent mistakes with the rm command
Create a function called rm that overrides the original command in your ~/.bashrc:
rm(){
mkdir -p /tmp/trash
mv $@ /tmp/trash
}
Now when you run rm, files go to /tmp/trash instead of disappearing permanently. You can recover them from there if needed.
Add those lines to the end of your ~/.bashrc, then run bash or open a new terminal to activate the change.
I like using /tmp for this because its contents are cleared on reboot. If you delete a file by mistake, you have until your next reboot to recover it. No manual cleanup required. You can use any folder you prefer, but then you need to empty it yourself or set up a cron job to do it.
To automatically clean out old files (say, anything not accessed in 30 days):
find . -name "*.log" -atime +30 -delete
Run this from your trash folder to remove stale files.
A better alternative today is trash-cli, which follows the FreeDesktop.org Trash specification and integrates with your desktop environment’s Trash. Install it with:
sudo apt install trash-cli
Then alias rm to trash-put:
alias rm='trash-put'
You can restore files with trash-restore, list trashed files with trash-list, and empty the trash with trash-empty. This is a more complete solution than the shell function above.
Securely deleting files in Linux
When you delete a file with rm, the data is still physically on the disk until the operating system reuses that space. Recovery software can often get it back. This matters if you are selling or giving away a drive.
Shred
The shred command overwrites a file multiple times with random data before deleting it, making recovery much harder:
shred [option] <target>
Useful options:
-uremoves the file after overwriting-nsets the number of overwrite passes (default is 3)-sshreds only the specified number of bytes-vshows progress-fchanges permissions if needed to allow writing-zadds a final pass of zeros to hide the fact that shredding occurred-xdoes not round file sizes up to the next block
To wipe a partition:
shred -vfz -n 10 /dev/sda1
Replace /dev/sda1 with the target device.
How to install shred
shred is part of coreutils and is almost certainly already installed. If for some reason it is not:
sudo apt-get install coreutils
Important caveat: shred on SSDs and NVMe drives
shred was designed for magnetic hard drives (HDDs). On SSDs and NVMe drives, it is unreliable because the drive’s wear-leveling controller writes to different physical cells than you might expect. The original data can persist in cells the controller has remapped away from.
For SSDs and NVMe drives, use these alternatives instead:
- SATA SSDs: Use
hdparmto issue an ATA Secure Erase command - NVMe drives: Use
nvme sanitizeornvme formatfrom thenvme-clipackage - Best practice: Use full-disk encryption (LUKS) from the start. When you need to securely erase, destroy the encryption header. The data becomes irrecoverable instantly
Conclusion
Deleting files and directories is one of the first things you learn when you get started with Linux, and the basics are straightforward. But as we covered here, there are plenty of scenarios that deserve extra attention.
rm and rmdir are the two commands you will use most often. I rarely use unlink day to day, but it has its place in scripts where you want to limit the operation to a single file for safety.
These commands work well in shell scripts too. A cron job that triggers a cleanup script can handle routine tasks like rotating old log files. Just test everything carefully before automating deletions, and always keep a current backup.
If you picked up something new here, leave a comment below. Feedback helps us keep improving.
Comments