这让我抓狂,因为我知道这很容易,但我似乎找不到解决办法。啊!我只需要在脚本中添加一个find命令,以便在运行新备份之前删除旧文件。我宁愿通过变量来控制这一点,而不是键入确切的命令。如果我在脚本中键入命令而不是使用变量,那么这个命令就能在脚本中工作。
FIND="/usr/bin/find"
BUILD="~/"
FINDOPTS="-type f -mtime +3 -exec rm -rf {} \;"
echo $find $BUILD $FINDOPTS
## remove the 2 week old backup
echo "Removing old backups... "
$FIND $BUILD $FINDOPTS如果我只是回显$FIND $BUILD $FINDOPTS命令,它就会显示出来,就像输入命令时所做的那样。唯一的区别是,当我键入它时,它实际上会运行。
输入/usr/bin/find ~/ -type f -mtime +3 -exec rm -rf {} \;很好。
我得到的错误是:
/usr/bin/find: missing argument to `-exec'有人能帮我解释一下为什么吗?谢谢!
发布于 2018-03-27 21:03:35
尽管有更好的总体解决方案,但在这个脚本中失败的原因如下:
FINDOPTS="-type f -mtime +3 -exec rm -rf {} \;"
^参数find正在等待的是字符;。由于;也是shell的命令分隔符(并不是偶然的),所以必须在shell命令中转义,因此通常输入\;。如果现在将此字符放入变量中,则shell将永远不会将其计算为分隔符。这样就逃不掉了。
在没有变量的情况下复制错误:
$ find /etc -exec ls "\;"
find: missing argument to `-exec'因此,只需将字符串替换为:
FINDOPTS="-type f -mtime +3 -exec rm -rf {} ;"发布于 2018-03-27 19:59:24
与find [...] -exec rm不同,我建议使用内置功能:
find [...] -delete从手册中:
-delete
Delete found files and/or directories. Always returns true. This executes
from the current working directory as find recurses down the tree. It will
not attempt to delete a filename with a ``/'' character in its pathname
relative to ``.'' for security reasons. Depth-first traversal processing
is implied by this option. Following symlinks is incompatible with this
option.(顺便说一句,您确实意识到,您的问题中的命令将删除自上次修改后三天以上的任何文件,是吗?)
https://unix.stackexchange.com/questions/433907
复制相似问题