using 'rm -rf' safely [duplicate]
Andrew Henderson
I'm fairly new to unix and I have seen a lot of warnings against using rm -rf.
Example: "But, always double check before you use rm -rf command, if you by mistake give this command in your home directory, or any other important directory, it will not ask to confirm, but it will delete everything there."
Can one still run this command followed by a directory name (rm -rf dirName) without deleting other important things if it is run from a home directory?
Generally, what are the safety rules while working with this command? What should one never type and where?
12 Answers
rm will only delete what you tell it, so in that sense, it's always safe to use. It will never randomly delete files on its own.
The danger is that it's easy to make a small typing mistake that ends up telling rm to delete a lot more than you intended.
As an example, imagine that you have a bunch of text files that you want to remove. Of course you can type rm *.txt to remove them. But what if you're distracted, or your finger slips on the keyboard, and you type rm * txt by mistake? You just removed every single file in the directory.
For this reason, I have rm aliased to rm -i, so it prompts me for each file I remove.
This command is not dangerous, but it does exactly what it’s told, which is to delete things. The safest way to use rm is to not give it unnecessary flags.
If you need to delete a file:
rm fileIf you need to delete a directory:
rm -r directoryYou should only add -f if you don’t care about the permissions on the file or directory. In that case, rm will not prompt you if it can delete a file that you do not have write access on.
You can also add the -i or -I flags to make rm ask you more often if you really want to delete the files you passed to it.