尝试 rm 时如何处理丢失的操作数错误

How to deal with missing operand error when trying to rm

我有以下代码

rm "$torrent"/*.{txt,nfo,jpg} && echo "removed \"txt,nfo,jpg\" files"

如果没有要删除的文件,我会收到 "missing operand" 错误,我想避免该错误,因为它会触发脚本的退出 1。

如果我有以下代码

rm -f "$torrent"/*.{txt,nfo,jpg} && echo "removed \"txt,nfo,jpg\" files"

即使没有文件被删除,rm 的计算结果也始终为真。

如果某些文件被删除,我想显示消息 "removed .. files"。如果没有文件被删除,我希望保持沉默,不抛出任何错误。

我玩过

find "$torrent" -type f -name "*.txt" -or -name "*.nfo" -or -name ".jpg" -delete && echo "files were deleted"

但即使没有文件被删除,它也始终评估为真。

只需将其重写为适当的 if 语句即可:

if rm "$torrent"/*.{txt,nfo,jpg}
then
  echo "removed \"txt,nfo,jpg\" files"
if

这允许您在 set -e 生效时对退出状态做出反应,而无需脚本退出