Linux shell脚本出现循环错误

我正在尝试创build一个for循环来删除超过15天的日志文件。 以下是我的脚本:

#!/bin/sh path="/home/test" logpath="$path/logs" for logfile in `find $logpath -mtime +14 -type f -name *.log` do echo "Deleting Log File: " $logfile rm -rf $logfile done 

它一直抛出一个错误:

 find: paths must precede expression Usage: find [-H] [-L] [-P] [path...] [expression] 

有任何想法吗?

请尝试这个 – 添加单引号

 #!/bin/sh path="/home/test" logpath="$path/logs" for logfile in `find $logpath -mtime +14 -type f -name '*.log'` do echo "Deleting Log File: " $logfile rm -rf $logfile done 

您可以使用findexec参数来摆脱for循环:

 find $logpath -mtime +14 -type f -name '*.log' -exec rm -rf {} \; 

或者像@Patryk Obara说的:

 find $logpath -mtime +14 -type f -name '*.log' -delete 

它隐式启用 – -depth

你可以像这样测试它:

 mkdir test cd test touch test1.log touch test2.log find . -type f -name '*.log' ls > test1.log test2.log find . -type f -name '*.log' -delete > empty 

对于这种工作,Logrotate是一个更好的选择,这是一个链接到它的文档 – http://www.linuxcommand.org/man_pages/logrotate8.html