Saturday, October 21, 2006

Out Damn Spot!

An interesting, yet common, question came up on the FreeBSD questions mailing list - "How do I delete a file that has a leading dash?" For instance, say you have a file called "-testing". Here's what happens if you try to delete it normally:



$ rm -testing

rm: illegal option -- t

usage: rm [-f | -i] [-dIPRrvW] file ...

unlink file



That's because the rm command thinks the '-t' is supposed to be an option (like the -f to force or the -r for recursive), and it doesn't recognize that option. Your first try might be to quote the file name:



$ rm "-testing"

$ rm \-testing


But that doesn't help, as it isn't the shell that's complaining but rather the rm command, which still sees the "-t" and doesn't understand it.



But as the rm man page reminds you, there are several easy ways around this problem. All of the following will work:



$ rm -- -testing

$ rm /home/usr/-testing

$ rm ./-testing



Because now the '-' isn't the first character. The '--' is a general way of telling pretty much any command that all options have ended and the rest of the command line should be processed as arguments to the command (often filenames). But the most obscure way of doing this had to be the answer using the find command to delete it by its inode number:



$ ls -i

 9232923 -testing

$ find . -inum 9232923 -exec rm {} \;



Isn't Unix wonderful? I was looking forward to seeing the answers to this question, and the thread didn't disappoint. There are so many ways of using the tools to solve problems. The find method would work for other, tough characters too.




No comments:

Post a Comment