The command line in Linux is powerful, but it also allows a user to do a lot of dangerous things. Removing files with a wildcard is one of those things where a misplace space or typoed command can remove a lot more files that expected. One of the worst feelings in the world is to run a “rm” command and have the server pause for a really long time. You begin to wonder “Did I just kill my server?”
Here are a couple of ways to remove files safely.
1. Use mv rather than rm
In this example, I have a lot of files and directories that I want to clean up, eg:
-rw-rw-r-- 1 cormac cormac 0 Jul 31 20:11 tmp1324 -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.2dSpsKw5wv drwx------ 2 cormac cormac 4096 Jul 31 20:13 tmp.5D5bLLDH3v drwx------ 2 cormac cormac 4096 Jul 31 20:13 tmp.6Lw6jmgEAr drwx------ 2 cormac cormac 4096 Jul 31 20:13 tmp.80sa84rbMg -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.9p9fWXpKCc -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.BVc4HD0Clm -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.EFge7HX3VA -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.EJOg10elMG -rw------- 1 cormac cormac 0 Jul 31 20:13 tmp.GBBOc9TOK9
I make a trash folder called deleted then use mv to move the files to that. For example:
mkdir ~/deleted && mv -v tmp* ~/deleted
All the deleted files will end up in the ~/deleted folder. If everything went ok you can just clean up that folder:
cd ~ && rm -rf deleted
This reduces the chance that you will remove too many files.
If something went wrong, just move the files back out of that folder to the original location.
2. Use the trash-cli utilities
There is a package called trash-cli that provide a few simple commands to remove files. It’s similar to the option above, but more polished. It provides a command line interface trashcan utility compliant with the FreeDesktop.org Trash Specification. It remembers the name, original path, deletion date, and permissions of each trashed file.
For Debian/Ubuntu, use apt-get command or apt command to install Trash-Cli.
$ sudo apt install trash-cli
For RHEL/CentOS, use YUM Command to install Trash-Cli.
$ sudo yum install trash-cli
For Fedora, use DNF Command to install Trash-Cli.
$ sudo dnf install trash-cli
You can then use “trash” in place of “rm”
For example, to remove all the tmp files that we had earlier:
trash tmp*
You can then use trash-list to see the contents of your trash folder, and trash-empty to clear out the folder.
If you need to recover files from trash use “restore-trash” to recover the file.
When you need to empty your trash bin, you can use “trash-empty” to remove all files from trash, or “trash-rm” to remove individual files.