bash 如何防止 rm 报告找不到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10247472/
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 to prevent rm from reporting that a file was not found?
提问by Village
I am using rm
within a BASH script to delete many files. Sometimes the files are not present, so it reports many errors. I do not need this message. I have searched the man page for a command to make rm
quiet, but the only option I found is -f
, which from the description, "ignore nonexistent files, never prompt", seems to be the right choice, but the name does not seem to fit, so I am concerned it might have unintended consequences.
我rm
在 BASH 脚本中使用来删除许多文件。有时文件不存在,因此它会报告许多错误。我不需要这个消息。我在手册页中搜索了一个命令来使rm
安静,但我找到的唯一选项是-f
,从描述中,“忽略不存在的文件,从不提示”,似乎是正确的选择,但名称似乎不合适,所以我担心它可能会产生意想不到的后果。
- Is the
-f
option the correct way to silencerm
? Why isn't it called-q
? - Does this option do anything else?
- 该
-f
选项是沉默的正确方法rm
吗?为什么不叫-q
? - 这个选项还有其他作用吗?
回答by chepner
The main use of -f
is to force the removal of files that would
not be removed using rm
by itself (as a special case, it "removes"
non-existent files, thus suppressing the error message).
的主要用途-f
是强制删除不会被rm
自己删除的文件(作为一种特殊情况,它“删除”不存在的文件,从而抑制错误消息)。
You can also just redirect the error message using
您也可以使用重定向错误消息
$ rm file.txt 2> /dev/null
(or your operating system's equivalent). You can check the value of $?
immediately after calling rm
to see if a file was actually removed or not.
(或您的操作系统的等价物)。您可以$?
在调用后立即检查 的值,rm
以查看文件是否被实际删除。
回答by Satya
Yes, -f
is the most suitable option for this.
是的,这-f
是最合适的选择。
回答by technosaurus
-f is the correct flag, but for the test operator, not rm
-f 是正确的标志,但对于测试操作员,而不是 rm
[ -f "$THEFILE" ] && rm "$THEFILE"
this ensures that the file exists and is a regular file (not a directory, device node etc...)
这确保文件存在并且是一个常规文件(不是目录、设备节点等...)
回答by vimdude
\rm -f file
will never report not found.
\rm -f file
永远不会报告找不到。
回答by Idelic
As far as rm -f
doing "anything else", it does force (-f
is shorthand for --force
) silent removal in situations where rm
would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.
至于rm -f
做“其他任何事情”,它确实会在要求您确认的情况下强制(-f
是--force
)静默删除rm
。例如,尝试从您可写的目录中删除您不可写的文件时。
回答by Niranjan
I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.
我对 cshell 有同样的问题。我唯一的解决方案是在我的脚本中创建一个与“rm”之前的模式匹配的虚拟文件。