Removing files with weird names

From Noah.org
Jump to navigationJump to search


If you have a file with command-line options embedded in the filename then you may have trouble deleting the file because the filename will be treated as command-line options. Be careful with the following example because you could delete a lot of files that you don't want deleted. The following is a trick to play on someone. This just creates an empty file:

touch -- -rf

Now list the new file:

$ ls -l -- -rf
-rw-r--r-- 1 noah noah 0 Jun 14 14:13 -rf

How do you delete the -rf file? If you run `rm -rf` then this would do nothing, thankfully.

The solution for deleting files that have command-line options embedded in their filenames is to give `rm` a hint that the string is not to be treated like an option. Most GNU tools will accept -- as the final option. This tells the option parser to stop interpreting the arguments following -- as more options. Stuff that comes after -- may look like options, but they won't be treated like options. So, to remove a file named "-rf" do this:

rm -- -rf

The previous example looks nasty, but it's fairly safe to play with, but you should see the potential for more trouble. If you don't see the potential, then do not run the following example. Even if you do see the potential you should understand how to fix the trouble before you run the following example. It's possible to make the filename even more destructive. DO NOT attempt to delete this file by running `rm -rf $HOME`!!! Thankfully, you cannot have a slash as part of a filename even if you quote it. Of course, nobody stupid enough to enter 'rm -rf /' should have root access in the first place. This example is destructive enough as it is even if we can't put a slash in the name.

touch -- "-rf \$HOME"

The fix for deleting this nasty file to run this:

rm -- "-rf \$HOME"