shell腳本自動刪除30天以前的文件(最新推薦)
shell腳本自動刪除30天以前的文件
需要刪除的文件目錄在/data/dbbak,
可以使用以下Shell腳本來實現(xiàn)定時刪除指定目錄下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設(shè)置定時任務(wù),例如每天凌晨3點執(zhí)行一次:
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 # 添加以下內(nèi)容 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
到此這篇關(guān)于shell腳本自動刪除30天以前的文件的文章就介紹到這了,更多相關(guān)shell刪除30天以前的文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實現(xiàn)釋放CentOS系統(tǒng)內(nèi)存的Shell腳本分享
這篇文章主要介紹了實現(xiàn)釋放CentOS系統(tǒng)內(nèi)存的Shell腳本分享,本文對一些小內(nèi)存的VPS特別有用,需要的朋友可以參考下2014-12-12
linux中編寫自己的并發(fā)隊列類(Queue 并發(fā)阻塞隊列)
這篇文章主要介紹了linux中編寫并發(fā)隊列類,功能有:并發(fā)阻塞隊列、有超時限制、有大小限制2013-12-12

