[英]Linux shell script for loop error
I'm trying to create a for loop to delete log files older than 15 days. 我正在尝试创建一个for循环来删除超过15天的日志文件。 Below is my script: 以下是我的脚本:
#!/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
It keeps throwing an error: 它不断抛出错误:
find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression]
Any ideas? 有任何想法吗?
Please try this - added single quotes 请试试这个 - 添加单引号
#!/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
You could use the exec
param of find
to get rid of the for loop: 您可以使用find
的exec
参数来摆脱for循环:
find $logpath -mtime +14 -type f -name '*.log' -exec rm -rf {} \;
or like @Patryk Obara says : 或者像@Patryk Obara说:
find $logpath -mtime +14 -type f -name '*.log' -delete
which enable -depth
implicitly. 它隐式启用-depth
。
You can test it like this : 你可以像这样测试它:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.