Linux 如何处理以连字符 (-) 字符开头的文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5677558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I deal with a filename that starts with the hyphen (-) character?
提问by crudcore
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 anythingwith this file, because every command I use to try to view, copy, or move it interprets the filename as an argument.
不知何故,在某些时候,我不小心在我的主目录中创建了一个名为“-s”的文件。它大约 500 kb,我不知道它是否包含重要数据。我想不出对这个文件做任何事情的任何方法,因为我用来尝试查看、复制或移动它的每个命令都将文件名解释为参数。
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.
另外,当我第一次向我的同事提出这个问题时,我们困惑了一段时间,直到有人无意中听到并问“你为什么不重命名它?” 在我向他解释 cp 和 mv 都认为文件名是一个参数所以它不起作用之后,他说“不,不是从命令行,从 Gnome 做。” 我羞怯地听从了他的建议,结果奏效了。但是,如果您没有窗口管理器并且命令行是唯一的选择,我仍然对如何解决这个困境感兴趣。
采纳答案by Michael Krelin - hacker
You can refer to it either using ./-filename
or some command will allow you to put it after double dash:
您可以使用它来引用它,./-filename
或者某些命令将允许您将它放在双破折号之后:
rm -- -filename
回答by paxdiablo
You can get rid of it with:
您可以通过以下方式摆脱它:
rm ./-s
The rm
command (at least under Ubuntu 10.04) even tells you such:
该rm
命令(至少在 Ubuntu 10.04 下)甚至会告诉您:
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.
有效的原因是因为rm
它不认为它是一个选项(因为它不以 开头-
)但它仍然指的是当前目录中的特定文件。
回答by Richard Pennington
You could use --, e.g.:
您可以使用 --,例如:
rm -- -file
回答by kurumi
besides using rm
, if you know a language, you can also use them. They are not affected by such shell warts.
除了使用之外rm
,如果你懂一门语言,你也可以使用它们。他们不受这种壳疣的影响。
Ruby(1.9+)
红宝石(1.9+)
$ ruby -rfileutils -e 'FileUtils.rm("-s")'
or
或者
$ ruby -e 'File.unlink("-s")'