How to delete files starting with a double hyphen?

I have some files on my Unix machine that start with

-- 

eg. --testings.html

If I try to remove it, I get the following error:

 cb0$ rm --testings.html rm: illegal option -- - usage: rm [-f | -i] [-dPRrvW] file ... unlink file 

I tried

 rm "--testings.html" || rm '--testings.html' 

but nothing works.

How to delete such files on the terminal?

+67
unix bash filenames
Apr 01 '09 at 15:57
source share
7 answers
 rm -- --testings.html 

The option -- tells rm to treat all further arguments as file names, not as parameters, even if they start with - .

This does not apply to the rm command. The getopt function implements it, and many (all?) UNIX-style commands treat it the same way: -- completes the processing of parameters and all that is a regular argument.

http://www.gnu.org/software/hello/manual/libc/Using-Getopt.html#Using-Getopt

+140
Apr 01 '09 at 15:59
source share
 rm -- --somefile 

While this works, this is an rm based solution using getopts to parse its options. There are applications that conduct their own analysis and will also fail (because they may not necessarily implement the logic β€œ -- means the end of options”).

Because of this, the solution you must pass through your skull is:

 rm ./--somefile 

It will always work, because in this way your arguments never begin with - .

Also, if you are trying to make really worthy shell scripts; you must technically put ./ in front of all your file name parameter extensions so that your scripts do not interrupt due to a funky file name input (or to prevent abuse / use to perform actions that they should not do: for example, rm will delete files, but skips directories, and rm -rf * deletes everything. Passing the file name " -rf " to the script or someone touch ~victim/-rf 'can thus be used to change its behavior with very bad consequences).

+55
Apr 01 '09 at 19:10
source share

Either rm -- --testings.html , or rm ./--testings.html .

+17
Apr 01 '09 at 16:01
source share
 rm -- --testings.html 
+7
Apr 01 '09 at 15:59
source share

Another way to do this is to use find ... -name "- *" -delete

 touch -- --file find -x . -mindepth 1 -maxdepth 1 -name "--*" -delete 
+4
Apr 02 '09 at 10:43
source share

For a more generalized approach to deleting files with impossible characters in the file name, one option is to use an index file.

It can be obtained using ls -i .

eg.

 $ ls -lai | grep -i test 452998712 -rw-r--r-- 1 dim dim 6 2009-05-22 21:50 --testings.html 

And to erase it with find:

 $ find ./ -inum 452998712 -exec rm \{\} \; 

This process can be useful when working with a large number of files with file name features, since it can be easily scripted.

+3
May 22 '09 at 18:56
source share
 rm ./--testings.html 

or

 rm -- --testings.html 
+1
Apr 01 '09 at 16:03
source share



All Articles