linux shell

关注公众号 jb51net

关闭
首页 > 脚本专栏 > linux shell > shell删除30天以前的文件

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

作者:森林番茄

该文章介绍了如何使用Shell脚本自动删除指定目录下30天以前的文件,并通过crontab设置定时任务,此外,还提供了如何使用Shell脚本删除Elasticsearch索引的参考,感兴趣的朋友一起看看吧

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天以前的文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文