我看到这个问题越来越流行了.我在下面回答了我自己的问题.什么说Inian是正确的,它帮助我更好地分析我的源代码.
我的问题出在了FIND而不是在RM.我的答案提供了一个代码块,我目前正在使用它来避免问题,当FIND找不到任何东西但仍会将参数传递给RM时,导致上面提到的错误.
以下老问题
我正在编写许多不同版本的相同命令.全部,执行但有错误/信息:
rm: missing operand
Try 'rm --help' for more information.
Run Code Online (Sandbox Code Playgroud)
这些是我正在使用的命令:
#!/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
Run Code Online (Sandbox Code Playgroud)
我确信所有这些都是正确的(因为它们都可以完成它们的工作),如果我手动运行它们,我就不会收到该消息,但是在.sh脚本中我会这样做.
编辑:因为我有许多这些RM,问题可能在其他地方.我正在检查所有这些.所有上述代码都有效,但最好的答案是标记的;)
Ini*_*ian 27
问题是find/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.
Run Code Online (Sandbox Code Playgroud)
此外,你不要尝试像下面粘贴的所有命令,简单的命令将满足你的需要.
将-r参数添加到xargs中
find "$BDIR" -type d -mtime +180 -print0 | xargs -0 -r rm -rf
Run Code Online (Sandbox Code Playgroud)
-f选项rm抑制rm: missing operand错误:
-f, --force
ignore nonexistent files and arguments, never prompt
Run Code Online (Sandbox Code Playgroud)