Ubuntu – How is ‘rm -rf /’ able to delete all files in the system

filesystemkernelrm

I haven't tried this command on Ubuntu (for obvious reasons) so I am not sure if Ubuntu will allow its execution. But it's famous for deleting everything. Just out of curiosity, what happens when the kernel and /bin are deleted? How does rm maintain a run time stack? How does rm manage to communicate with the file system and complete deletion? How does it communicate with hardware?

Best Answer

It doesn't matter that /bin/rm is deleted. It's only being run once and by that point it's all loaded in memory, as is everything else required to keep sending deletes to the filesystem and disk.


Sidebar/Update: Per David Hoelzer's answer (and mentioned in the comments), the inode the hardlink /bin/rm used to point to would remain right up until rm finished (because Linux holds in an open state) but that fact is irrelevant; the state of the disk doesn't matter at all.

The binary is loaded into memory before it is run. Even if you could manually destroy the rm disk data, it wouldn't affect or stop the deletion from completing (assuming you don't otherwise make the disk unavailable).

No idea what an inode or hardlink are? This is the answer where I worked it out.


Anyway, this is also why you can delete the package for the current kernel without the computer imploding. As long as you install a different version, it'll be able to boot up.

Again, this works because rm is only called once. The following would fail after /bin/rm died because it calls it once for every filename:

find / -exec rm {} \;

That said, find / -exec rm -rf {} + and find / -print0 | xargs -0 rm -rf would also both likely fail because they both have argument limits, meaning they would only delete a number of files before being called again. At some point along the journey, /bin/rm could expire (and be released) before the rest of the files were deleted. It's not guaranteed though. If /bin/ were the last directory entered, these methods could work.