Something to avoid with the recurrsive rm -rf command

We all know about the powerful but dangerous rm -rf command, that will recursively remove all files within a directory. If run in the wrong directory by accident, it can wipe it out and if run from /, you will lose every last bit of your operating system. For many, it is a command best avoided as there are other options.

I am a person that in the terminal, am in the habit of hitting the up-arrow-key to access a previously entered command in order to repeat it.
The other day, i did something unusual and deviated from my usual way of doing things. In cleaning my cache, instead of entering rm -rf /home/.config/cache I cd'd to the cache folder and then just entered rm -rf. No problems, made the cache folder clean n shiny.
But later, when I hit the up-arrow to redo a command, I very nearly hit enter a moment too soon. Since the rm -rf command was all there was on that line, it would have wipe out all data in my Home Directory and would not ask "Are you sure? (y/n)."
If you are a person that up-arrow keys in terminal, a quick tip: only ever use the rm -rf command with the file path. That way if you bap it by accident, it will only try to remove the contents of a folder which already has been cleaned.
And if ever you do cd to the directory, then run the command before you realize what you have done; It would be wise to open the bash_history file in your home folder and delete that line afterward to prevent horrors.

6 Likes

3 posts were split to a new topic: Discussing Something to avoid with the recurrsive rm -rf command

Update:
@FrenchPress noted the following:
https://www.phoronix.com/scan.php?page=news_item&px=UEFI-rm-root-directory

The rm -rf command can even perma-brick UEFI systems.

2 Likes

There is an easy solution to this that I have implemented. Edit the bashrc file with the following command. Make sure to backup the file first.

$ sudo cp .bashrc .bashrc.bak
$ sudo nano .bashrc

Then add the following 2 lines under aliases

alias rm='rm -i'
alias rmdir='rm -ri'

Save the file and exit nano. Reload bashrc with the command
$ source=~/.bashrc

Now next time you try to remove a file with rm, it will ask you for confirmation. And if you want to remove a directory, type rmdir instead of 'rm -rf' and it will prompt you for confirmation before it deletes.

That's it.

2 Likes