My blog has moved!

You should be automatically redirected. If not, visit
http://benohead.com
and update your bookmarks.

Sunday, October 16, 2011

Remove files starting with a dash

Assume you have a file called -exclude or --exclude and you want to delete it. Just using rm -exclude or rm --exclude will not work since rm will handle -exclude or --exclude as an option (like every argument starting with a dash).

Using single quotes (i.e. rm '-exclude' will not help either since all it does is escape characters in the string which is then again interpreted as an option.

So what's the solution?

First the hard, interesting and stupid way... If we can't use the name of the file to delete it, we need to find something else... Maybe an ID... Like the inode index number of the file !
So let's get it via ls: ls -i. Let's assume we got the index number 1835887. Now we have the index number of the file, we can search for the file using find and delete it: find . -inum 1835887 -exec rm -f {} \;

Wait, if it worked searching for the file with find and deleting the file maybe we don't need an ID but can just use the file name. Let's try: find . -name '-exclude' -exec rm -f {} \;

It works !!!

So now, we've spent enough time figure out complex and stupid ways the delete those files, let's get back to the basics and .... RTFM... Read the fucking manual: man rm.

What do we see there:

To remove a file whose name starts with a '-', for example '-foo',  use one of these commands:

  rm -- -foo

  rm ./-foo


Doh !! It was actually that simple, yet it was fun wasting time with find and inode... ;-)

No comments:

Post a Comment