2010/09/27

Deleting files that start with a dash in UNIX

Today I inadvertently ended up with a file that started with a dash and I tried to rm it.

The Bad Way

Ives ~ $ rm --something
rm: unknown option -- something
Try `rm ./--something' to remove the file `--something'.
Try `rm --help' for more information.
Ives ~ $ rm '--something'
rm: unknown option -- something
Try `rm ./--something' to remove the file `--something'.
Try `rm --help' for more information.
Ives ~ $ # HELP!!!
That clearly doesn't work.

The Good Way

The answer is quite simple: address the file in such a way that it no longer has a dash as the first character. In fact, carefully reading the rm error message will tell you this:

Try `rm ./--something' to remove the file `--something'.

So the solution is simple:

Ives ~ $ rm ./--something
Ives ~ $

The Good Way 2

Another way by Nathan Samson...
Ives ~ $ rm -- --something
Ives ~ $
This works because -- signals the end of option processing in a lot of Unix utilities, including touch, rm, ... and also all programs that use getopt(3) for their option processing.

1 comment:

  1. "rm -- --something" is also working

    "In the *nix world, there’s a practice that anything after double-hyphens -- should be read as a filename, even if the name contains hyphens (e.g. cmd -- -FILE-). If the arguments list ends with a single-hyphen, input should be read from standard input." (http://www.antoarts.com/designing-command-line-interfaces/)

    ReplyDelete