Shell script automatically deletes files from 30 days ago
The file directory that needs to be deleted is in /data/dbbak.
You can use the following shell script to implement the timely deletion of files 30 days ago in the specified directory:
vi /opt/
#!/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
Set up timed tasks using crontab, for example, perform once every day at 3 a.m.:
0 3 * * * sh /opt/
This will automatically delete files from the specified directory 30 days ago every day.
Supplement: Linux deletes elasticsearch index on a timely basis according to date
Linux deletes elasticsearch index on date time
Use sh script to delete
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
Add timer
crontab -e # Add the following00 03 * * * /usr/local/elk/elasticsearch-8.17.0/delete_es_by_day.sh > /dev/null 2>&1 #Verify that it has been addedcrontab -l|tail -2
refer to:elasticsearch deletes indexes according to date time
refer to:removing-old-indices-in-elasticsearch
This is the article about automatically deleting files from 30 days ago in shell scripts. For more relevant shell delete files from 30 days ago, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!