I inadvertently created a file called -r in my home directory. Now I cannot get rid of it:

rm -rf rm: missing operand Try 'rm --help' for more information. 

Other attempts:

rm /-/r rm: cannot remove ‘/-/r’: No such file or directory 

Another one:

rm \-r rm: missing operand Try 'rm --help' for more information. 

Is there a way to remove this file without deleting the whole directory?

4

4 Answers

There are many ways of doing this:

  1. Use the -- which signifies the end of option flags and the beginning of the list of arguments for many programs (including rm).

    rm -- -r 
  2. Use the full path

    rm /home/you/directory/-r 

    or, from the same directory (your current directory is referred to as .):

    rm ./-r 
  3. Use find

    find . -name "-r" -exec rm {} \; 

    or, to get all such files

    find . -name "-*" -exec rm {} \; 
  4. Use an ugly hack. Move everything to a different directory (this will fail for the -r file for the same reason as rm does) and then delete the original directory (which will remove the file) and move everything back again. So, assuming your -r file is in ~/foo:

    $ mkdir ~/bar $ for f in *; do mv "$f" ../bar/; done mv: invalid option -- 'r' Try 'mv --help' for more information. $ rm -rf ~/foo $ mkdir ~/foo && cd ~/foo $ mv ~/bar/* . $ rmdir ~/bar 
2

In this case you have to use the double-dash (--) in your command arguments.

The purpose of it is to tell to the command that what's follow has not to be taken as an argument to the command but a simple input. In the case of rm, a file or directory name.

So type rm -- -r and you should get rid of this file.

You can also delete such files (starting with a '-') with this command:

rm ./-r 

See the rm man page:

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

rm -- -foo rm ./-foo 

Or you could specify the full path of the directory in the rm command,

Example:

rm -rf ~/Desktop/-r