190

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.

  • Is the -f option the correct way to silence rm? Why isn't it called -q?
  • Does this option do anything else?
4

6 回答 6

248

的主要用途-f是强制删除本身不会删除的文件rm(作为一种特殊情况,它“删除”不存在的文件,从而抑制错误消息)。

您也可以使用重定向错误消息

$ rm file.txt 2> /dev/null

(或您的操作系统的等效项)。$? 您可以在调用后立即检查文件的值,rm以查看文件是否实际被删除。

于 2012-04-20T16:58:13.953 回答
83

是的,-f这是最合适的选择。

于 2012-04-20T13:45:58.953 回答
33

-f 是正确的标志,但对于测试运算符,不是 rm

[ -f "$THEFILE" ] && rm "$THEFILE"

这确保文件存在并且是常规文件(不是目录、设备节点等...)

于 2013-06-12T20:47:49.570 回答
17

\rm -f file永远不会报告未找到。

于 2012-10-24T16:55:04.333 回答
6

至于rm -f做“其他任何事情”,它确实会在需要您确认的情况下强制(-f是简写)静默删除。例如,当尝试从您可写的目录中删除您不可写的文件时。--forcerm

于 2012-04-20T16:51:23.080 回答
-10

我对 cshell 有同样的问题。我唯一的解决方案是在我的脚本中创建一个与“rm”之前的模式匹配的虚拟文件。

于 2014-05-28T17:53:22.620 回答