UNIX

UNIX – How do you delete a file whose name begins with “-” (hyphen a.k.a. dash or minus)

  • How do you remove a file whose filename begins with a dash (hyphen or minus) -? You are ssh’d into a remote OSX server and you have this file in your directory:
bash code
tohru:~ $ ls -l
total 8
-rw-r--r--    1 me  staff  1352 Aug 18 14:33 --help
...
  • How in the world can you delete –help from a CLI? This issue is something that you come across in different forms on occasion, these files are easy to create, but hard to get rid of you have tried using backslash.
bash code
rm \-\-help

I have tried quotes

bash code
rm "--help"
  • How do you prevent the minus (dash or hyphen) character to be interpreted as an option?

  • Use “–” to make rm stop parsing command line options, like this:
bash code
rm -- --help

Or you can do

bash code
        rm ./--help

Use find to do it:

bash code
           find . -name '--help' -delete
  •  If you have more then a few files like this that you can delete you can get a preview list of the files by simply running find without the -delete option first, and then if the list of files look good just run it again with -delete.
  • In fact, you avoiding rm in favor of find (especially with preview first) that will help you to avoid mistakes with rm * that will inevitably bite you some day.
  •  That find will recurse through all your subdirectories, so you might want to run it with a subdirectory depth constraint like this:
bash code
find . -maxdepth 1 -name '--help' -delete
  • which limits the find to the current directory.
READ  BASH - What is the real difference between “apt-get” and “aptitude”? (How about “wajig”?)

bash code
find . -inode <inode> -exec rm {}\;

TAB: menu-complete             # Tab: Cycles through the command
"\e[Z": menu-complete-backward # Shift-Tab: Cycles backwards

javascript code
[email protected] ~ $ touch -- "--yo yo"
[email protected] ~ $ ls
bin  --yo yo

[email protected] ~ $ find . -name "*--yo yo*"
./--yo yo

[email protected] ~ $ find . -name "*--yo yo*" -delete
[email protected] ~ $ ls
bin  

A brutal solution:

bash code
perl -e "unlink '--help' or die 'Could not unlink.';"

perl -e "rmdir '-d' or die 'Could not rmdir.';"

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X