错误' rm:缺少操作数'与...一起使用时找到'命令

时间:2016-04-14 08:47:31

标签: bash rm operand

我看到这个问题越来越流行了。 我在下面回答了我自己的问题。 什么说 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,问题可能在其他地方。我正在检查所有这些。以上所有代码都有效,但最佳答案是标记的代码;)

3 个答案:

答案 0 :(得分:27)

问题是当使用rankingfind/grep时,只有在前一个命令成功时才需要确保运行管道命令。与上面的情况类似,如果xargs命令不产生任何搜索结果,则使用空参数列表调用find命令。

rm

man页面
xargs

此外,你不要尝试像下面粘贴的所有命令,这些命令将符合你的需要。

-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. 参数添加到xargs中,如

-r

答案 1 :(得分:4)

-f的{​​p} rm选项会抑制rm: missing operand错误:

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

答案 2 :(得分: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字节,这意味着我不再需要文件夹。

如果您正在查找&#39;如果没有使用&rm:缺少操作数&#39;,则可能无法在RM中搜索,而不是在FIND本身中搜索。 使用FIND删除文件的好方法是我觉得可以与您分享。