How do I deal with a filename that starts with the hyphen (-) character?

LinuxBash

Linux Problem Overview


Somehow, at some point, I accidentally created a file in my home directory named '-s'. It is about 500 kb and I have no idea if it contains important data or not. I cannot figure out any way to do anything with this file, because every command I use to try to view, copy, or move it interprets the filename as an argument.

I've tried putting it in quotes, escaping it with a backslash, a combination of the two, nothing seems to work.

Also, when I first posed this question to my coworkers, we puzzled over it for a while until someone finally overheard and asked "why don't you just rename it?" After I explained to him that cp and mv both think the filename is an argument so it doesn't work, he said "no, not from the command line, do it from Gnome." I sheepishly followed his advice, and it worked. HOWEVER I'm still interested in how you would solve this dilemma if you didn't have a window manager and the command line was the only option.

Linux Solutions


Solution 1 - Linux

You can refer to it either using ./-filename or some command will allow you to put it after double dash:

rm -- -filename

Solution 2 - Linux

You can get rid of it with:

rm ./-s

The rm command (at least under Ubuntu 10.04) even tells you such:

pax@pax-desktop:~$ rm -w
rm: invalid option -- 'w'
Try `rm ./-w' to remove the file `-w'.
Try `rm --help' for more information.

The reason that works is because rm doesn't think it's an option (since it doesn't start with -) but it's still referring to the specific file in the current directory.

Solution 3 - Linux

You could use --, e.g.:

rm -- -file

Solution 4 - Linux

besides using rm, if you know a language, you can also use them. They are not affected by such shell warts.

Ruby(1.9+)

$ ruby -rfileutils -e 'FileUtils.rm("-s")'

or

$ ruby -e 'File.unlink("-s")'

Solution 5 - Linux

Just for fun you could also use/abuse find.

find . -name "-s" -delete

or

find . -name "-s" -exec cat {} \;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncrudcoreView Question on Stackoverflow
Solution 1 - LinuxMichael Krelin - hackerView Answer on Stackoverflow
Solution 2 - LinuxpaxdiabloView Answer on Stackoverflow
Solution 3 - LinuxRichard PenningtonView Answer on Stackoverflow
Solution 4 - LinuxkurumiView Answer on Stackoverflow
Solution 5 - LinuxAmos BakerView Answer on Stackoverflow