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設置定時任務,例如每天凌晨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 # 添加以下內容 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天以前的文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
shell腳本連接、讀寫、操作mysql數(shù)據庫實例
這篇文章主要介紹了shell腳本連接、讀寫、操作mysql數(shù)據庫實例,本文包含連接、讀取、插入、創(chuàng)建數(shù)據庫等操作示例,需要的朋友可以參考下2014-08-08Linux下查找后門程序 CentOS 查后門程序的shell腳本
這篇文章主要介紹了Linux下查找后門程序 CentOS 查后門程序的shell腳本,需要的朋友可以參考下2014-09-09shell腳本自動化創(chuàng)建虛擬機的基本配置之tomcat--mysql--jdk--maven
這篇文章主要介紹了shell腳本自動化創(chuàng)建虛擬機的基本配置之tomcat--mysql--jdk--maven的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05