删除/data/logs目录下超过2天的log文件
!!!删除文件时应该非常谨慎,以免误删重要文件!!
设置每分钟执行一次
* * * * * sh /data/rm_audit_log.sh
方式1
# 查找满足条件的文件,并删除 find /data/logs -type f -name "*log*" -mtime +1 -print0 | xargs -0 rm # 如果find找到符合的文件,删除之; # 如果find找不到符合的文件,rm命名没有参数,报错rm: missing operand。
方式2
find /data/logs -type f -name "*log*" -mtime +1 -exec rm -rf {} \; # 如果find找到符合的文件,删除之; # 如果find找不到符合的文件,则不会删掉文件。
方式3(推荐)
#!/bin/bash # 查找符合条件的文件,并将文件名保存到变量中 # -mmin +120 删除最后修改时间为2小时前的 files=$(find /data/logs -type f -name "*log*" -mtime +1) # 遍历变量中的文件名,对每个文件进行检查并删除符合条件的文件 for file in $files; do if [[ $file == *"log"* && $file == *"my-application"* ]]; then rm -f "$file" echo "Deleted file: $file" fi done

浙公网安备 33010602011771号