Removing a File Beginning With Dash –

I get this a lot from friends and Google is full of examples, but here it is again.

If you have a file that begins with a hyphen (one of these: -) you’ll have a tough time removing it unless you remember something simple from Command Line 101. In most CLI environments, your shell has two ways to access a file: relative path and absolute path.

See, all I had to do was type that and 90% of you just went “Durr!” and removed your file.

For the rest of you, just refer to the file by it’s full path. Example:

/tmp$ ls -la|grep ^\-
-rw-r--r-- 1 bob bob 0 2009-10-28 12:50 -somefile

Oh look, I have a file in /tmp called -somefile. What ever shall I do to remove it?

/tmp$ rm -somefile
rm: invalid option -- s
Try `rm ./-somefile' to remove the file `-somefile'.
Try `rm --help' for more information.

Oh my! That didn’t work at all! The rm command thinks I’m passing it a flag called -somefile. Conveniently, rm knows I’m not very bright and tells me how to remove it!

/tmp$ rm ./-somefile
/tmp$

Well blow me down! Alternately, you can refer to the file with the full path:

/tmp$ rm /tmp/-somefile
/tmp$

The key is to remember that the shell knows where you are, but doesn’t know what you want. If you imply that you want to delete something, the shell does it’s best guess. In this case, it guesses wrong because rm command flags take precedence over arguments. If you are explicit in what you want, the shell does not have to guess.

Of course, being fully explicit means issuing the full command for rm:

/bin/rm /tmp/-somefile

But you have to know where rm lives. You can guess, or you can find it with which:

$ which rm
/bin/rm

But how do you know where which is?

``/usr/bin/which which` rm` /tmp/-somefile

Ok, that’s dumb. Go remove your file.

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, linux, Unix. Bookmark the permalink.

Leave a Reply

Your email address will not be published.