当前位置: 代码网 > 服务器>服务器>Linux > shell脚本自动删除30天以前的文件(最新推荐)

shell脚本自动删除30天以前的文件(最新推荐)

2025年04月24日 Linux 我要评论
shell脚本自动删除30天以前的文件需要删除的文件目录在/data/dbbak,可以使用以下shell脚本来实现定时删除指定目录下30天以前的文件:vi /opt/cleanfile.sh#!/bi

shell脚本自动删除30天以前的文件

需要删除的文件目录在/data/dbbak,
可以使用以下shell脚本来实现定时删除指定目录下30天以前的文件:
vi /opt/cleanfile.sh

#!/bin/bash
target_dir="/data/dbbak"
timestamp=$(date +%s -d "30 days ago")
for file in "${target_dir}"/*
do
    if [[ -f "${file}" && $(date +%s -r "${file}") -lt "${timestamp}" ]]
    then
        rm -f "${file}"
        echo "deleted file: ${file}"
    fi
done

使用crontab设置定时任务,例如每天凌晨3点执行一次:
0 3 * * * sh /opt/cleanfile.sh
这样就可以每天自动删除指定目录下30天以前的文件了。

补充:linux按照日期定时删除elasticsearch索引

linux按照日期定时删除elasticsearch索引

使用sh脚本删除

searchindex=filebeat
elastic_url=192.168.98.136
elastic_port=9200
saveday=7
date2stamp () {
    date --utc --date "$1" +%s
}
datediff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp $1)
    dte2=$(date2stamp $2)
    diffsec=$((dte2-dte1))
    if [ ${diffsec} -lt 0 ]; then abs=-1; else abs=1; fi
    echo $((diffsec/sec*abs))
}
for index in $(curl -s "${elastic_url}:${elastic_port}/_cat/indices?v" | grep  "${searchindex}" | grep "_log-20[0-9][0-9]\.[0-1][0-9]\.[0-3][0-9]" | awk '{print$3}'); do
        date=$(echo ${index##*-} | sed 's/\./-/g')
        cond=$(date +%y-%m-%d)
        diff=$(datediff -d $date $cond)
        echo -n "${index}****diff**** (${diff})"
        if [ $diff -gt ${saveday} ]; then
          echo "!!!delete ${index}"
          curl -xdelete "${elastic_url}:${elastic_port}/${index}?pretty"
        else
          echo ""
        fi
done

添加定时

crontab -e
# 添加以下内容
00 03 * * * /usr/local/elk/elasticsearch-8.17.0/delete_es_by_day.sh > /dev/null 2>&1
#验证是否已添加
crontab -l|tail -2

参考: elasticsearch按照日期定时删除索引
参考: removing-old-indices-in-elasticsearch

到此这篇关于shell脚本自动删除30天以前的文件的文章就介绍到这了,更多相关shell删除30天以前的文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com