Prevent Accidental Deletion with rm -rf *

Date March 13, 2008

Spotted this tip on the programming subreddit, and I thought it was too clever not to post.

Creating a file named -i will prevent an errant rm -rf * from wiping out the directory containing it. How? The * expands -i to your command line, and your rm -rf * becomes rm -rf -i *!

See it in action:


[mshade@slicebot ~]$ cd test/
[mshade@slicebot test]$ touch — -i
[mshade@slicebot test]$ touch 1 2 3 a b c
[mshade@slicebot test]$ ls
-i 1 2 3 a b c
[mshade@slicebot test]$ rm -rf *
rm: remove regular empty file `1′?

So how do you actually delete this odd file?

rm -- -i

The ‘–’ option tells it to stop looking for flags and treat the rest of the command line as operands.

Note that this trick won’t work if you specify an absolute path (as in rm -rf ~/test/) — only when you are within the directory. I’d recommend dropping this in your home and / directories.

Enjoy!

With credit to probablycorey.

2 Responses to “Prevent Accidental Deletion with rm -rf *”

  1. Prevenir un rm -rf * accidental « Arbol Charyou said:

    [...] Prevent Accidental Deletions with rm -rf * [...]

  2. e-yes said:

    >Note that this trick won’t work if you specify an absolute path

    Why not to use ‘less rectal’ solutions?:)

    apt-get install safe-rm

    or (FreeBSD-way):

    alias rm=’rm -i’

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>