Myrtle Street Labs
experiments in technology and culture
unix shell tricks: one way to avoid deleting important files by accident
Categories: bag o' tricks

asteriskWhen I was in college I once had several files in my home directory with semicolons in the middle of their names.  I decided to remove them all at once with this command:

$ rm *;*

The response from the shell was this:

sh: *: command not found

Then, to my horror, when I listed the directory I could see all my files were gone.

The unix nerds in the audience will have already noticed what happened.  You see, the semicolon is the magic character that ends a command line.  I had told the shell to remove all my files then run a command called *.

Game over, at least for all the files in my home directory.

This story came up in a particularly geeky thread yesterday on Facebook, and Nick Shapiro told me a trick he learned from our mutual friend Greg Sutter.

Put a file called “-i” in directories containing vital files.  If you run “rm *” the file called “-i” tricks rm into running in “interactive” mode, which gives you a chance to bail out.

Here’s an example:

$ mkdir tmp; cd tmp
$ touch ./-i
$ touch foo bar baz
$ rm *
rm: remove regular empty file `bar'?

Now you have a chance to notice what happened and hit control-c to exit.

To remove the file, use

$ rm ./-i

Another handy related trick: a perl one-liner is also a great way to remove files with tricky names:

$ perl -e "unlink('-i');"

This trick also works great for files with other inconvenient names, like -, –, ;, >, and <, for which the “./” technique above doesn’t work.

UPDATE:

My friend Joe Ardent points out something I had forgotten: The GNU convention is to ignore any arguments after “–” in the argument list.  Thus, you can also do this:

$ touch -- -i
$ rm -- -i

Joe also reminds me that you can escape special shell characters using the backslash character. Thus, “rm \<” works, which is simpler than the perl one liner.  Just when you think you’re an expert in something…

2 Comments to “unix shell tricks: one way to avoid deleting important files by accident”

  1. bill says:

    Put this in your .bashrc

    alias rm=’rm -i’
    alias mv=’mv -i’
    alias cp=’cp -i’

    override with

    \rm *
    \mv *
    \cp *

    • John Blair says:

      Yeah, I know about that… what I thought was cool about this hack is that it allows the interactive option to be added per-directory, and only to stop you if you accidentally type “rm *”. Not the most useful thing, but I posted due to the sheer ridiculous cleverness of it.

Leave a Reply