当与“find”命令一起使用时出现错误“rm: missing operand”。

28

我看到这个问题很受欢迎。 下面是我自己的答案。 Inian所说的是正确的,它帮助我更好地分析了我的源代码。

我的问题在于FIND而不在于RM。我的回答给出了一个代码块,我目前正在使用它来避免当FIND什么也没找到但仍会传递参数给RM时引起上述错误。

以下是旧问题

我写了很多不同版本的相同命令。 所有的命令都能执行,但是会有一个错误/提示:

rm: missing operand
Try 'rm --help' for more information.

这些是我正在使用的命令:

#!/bin/bash
BDIR=/home/user/backup
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} +
find "$BDIR" -type d -mtime +180 -print -exec rm -rf {} \;
find "$BDIR" -depth -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -depth -type d -mtime +180 -print -exec rm -rf {} +

find $BDIR -type d -mtime +180 -print0 | xargs -0 rm -rf

DEL=$(FIND $BDIR -type d -mtime +180 -print)
rm -rf $DEL

我相信它们都是正确的(因为它们都能完成自己的工作),如果我手动运行它们,我不会收到那个消息,但在.sh脚本中却会。

编辑:由于我有很多这样的RM,问题可能出在其他地方。我正在检查它们。以上所有代码都有效,但最佳答案是标记的那个;)


可能是Ignore empty result for xargs的重复问题。 - jazzmax
你的问题应该保持为一个问题。我会撤销你的编辑,但我希望给你一个机会,让你把新的文本作为答案发布,然后再回滚更改。(显然,它仍将在编辑历史记录中可用,您可以通过单击“编辑(日期)”通知来获取它。) - tripleee
@tripleee 你好,我编辑了这篇文章。希望我做得没问题!感谢你的注意。 - aPugLife
这是一个改进,不过我仍然会想要删除评论,或者将其移动到你的答案中。但还是感谢您的修复! - tripleee
3个回答

48

使用find/grepxargs时,需要确保只有在前一个命令成功运行后才运行管道命令。就像上面的情况一样,如果find命令没有产生任何搜索结果,则会用空参数列表调用rm命令。

xargsman

 -r      Compatibility with GNU xargs.  The GNU version of xargs runs the
         utility argument at least once, even if xargs input is empty, and
         it supports a -r option to inhibit this behavior.  The FreeBSD
         version of xargs does not run the utility argument on empty
         input, but it supports the -r option for command-line compatibil-
         ity with GNU xargs, but the -r option does nothing in the FreeBSD
         version of xargs.

此外,您不需要尝试所有命令,只需粘贴下面的简单命令即可满足您的需求。

-r参数添加到xargs中,如下所示:

find "$BDIR" -type d -mtime +180 -print0 | xargs -0 -r rm -rf

13

-f选项可以抑制rm: missing operand错误。

-f, --force 
       ignore nonexistent files and arguments, never prompt

2
当没有任何需要运行的时候,不调用rm更符合语义。 - Ro Achterberg

1

经过研究,我喜欢使用的命令是:

HOME=/home/user
FDEL=$HOME/foldersToDelete
BDIR=/backup/my_old_folders
FLOG=/var/log/delete_old_backup.log
find ${BDIR} -mindepth 1 -daystart -type d -mtime +180 -printf "%f\n" > ${FDEL}
if [[ $? -eq 0 && $(wc -l < ${FDEL}) -gt 0 ]]; then
    cd ${BDIR}
    xargs -d '\n' -a ${FDEL} rm -rf
  LOG=" - Folders older than 180 were deleted"
else
  LOG=" - There aren't folders older than 180 days to delete"
fi
echo ${LOG} >> ${FLOG}

为什么?我搜索所有旧文件夹,无论它们的命名是否带有空格,并将它们全部打印到一个文件中,以便删除。如果该文件大于0字节,则说明有我不需要的文件夹。

如果您的“FIND”出现“rm:missing operand”的错误,则可能不是在RM中搜索,而是在FIND本身中搜索。使用FIND删除文件的好方法就是我想与您分享的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接