Question

This question states:

It is amazing how many users don't know about the rm ./-rf or rm -- -rf tricks.

I am afraid to try these, but curious as to what they do. They are also very difficult to search...

Can someone enlighten me?

Was it helpful?

Solution

rm ./-rf and/or rm -- -rf would attempt to remove a file named, specifically, -rf

The only trick here is that you normally can't delete a file that starts with a "-" because the command will assume it's a command argument. By preceding the file with a full path, or using the -- option (which means, end all options) the command will no longer assume it's an argument.

It should be noted that the -- version of this trick may or may not work with all shell commands either, so it's best to use the first version.

OTHER TIPS

If you have a file named -rf in your directory, it is difficult to remove that file if you don't know the trick. That's because:

rm -rf

supplies two command line options (-r and -f) as a single argument, and tells rm to recursively and forcibly remove things.

If you write:

rm ./-rf

the argument does not start with a dash any more, so it is simply a file name. Similarly, by common (but not universal) convention, -- marks the end of the option arguments and anything afterwards is no longer an option (which usually means it is a file name). So:

rm -- -rf

removes the file because rm knows that the arguments that follow the -- are file names, not options for it to process.

The file -rf is even more dangerous if you use wildcards:

rm *rf*

Suddenly, this will remove directories as well as files (but won't harm the file -rf).

Not a complete answer, as I think the other answers give good explanations.

When I'm unsure what a given rm invocation is going to delete, I try to remember to simply ls the file list first to make sure it is actually what I want to delete:

$ ls -rf
-rf  ..  .
$ 

OK, clearly thats not right, lets try again:

$ ls ./-rf
./-rf
$

Thats better. Lets do a history replacement of ls with rm -v (-v just for extra paranoia/checking) and do the actual delete:

$ rm -v !!:*
rm -v ./-rf
removed `./-rf'
$ 

This also works nicely with wildcards, brace expansions, etc, when you're not sure what the expansion will be exactly.


Also if you're wondering how files like -rf get created in the first place, its astonishingly easy if you mess up a redirection a bit:

$ ls
$ echo > -rf
$ ls
-rf
$
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top