Sunday, May 5, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 4841  / 3 Years ago, tue, november 9, 2021, 2:43:11

I have some folder with files with the names as "example_YY_MM_DD-HH.zip" and I have 3 backups per day. I need this:



1) For backups older than 1 week I need only one per day (at midnight '00' at HH)



2) For backups older than month I need only one backup per week.



3) For backups older than one year I need only one backup per month (first day of month)



I have only this and I dont know what put to IF part.



Thanks



#!/bin/sh
export NOW=$(date +"%d-%m-%Y")
export OUTPUT=/media/backup/logs/delete-old.txt
export BACKUP_DIR=

for file in $BACKUP_DIR
do
if $file

fi
done

More From » command-line

 Answers
6

This should work (if you set the correct full or relative path it is currently on the directory test)



#! /bin/bash

nowday=$(date +"%d")
nowmonth=$(date +"%m")
nowyear=$(date +"%y")

#number of days since 1 Jan 1970 (today)
nowdays=$(($(date --date="20$nowyear-$nowmonth-$nowday" +"%s")/86400))

backup_dir="test/*"
#echo $backup_dir
for file in $backup_dir
do
hour=${file: -6: -4}
day=${file: -9: -7}
month=${file: -12: -10}
year=${file: -15: -13}
#number of days since 1 Jan 1970 (file)
days=$(($(date --date="20$year-$month-$day" +"%s")/86400))
if ((days < nowdays-365)); then
# more than one year
if ((10#$day == 1))&&((10#$hour == 0)); then
#day is 1 hour is 0 (we keep) use this space if you want to copy or something!
:
else
#Wrong day or hour
rm $file
fi
else if ((days < nowdays-31)); then
# more than one month (31 days)
if (((10#$day == 1))||((10#$day == 8))||((10#$day == 15))||((10#$day == 22))||((10#$day == 29)))&&((10#$hour == 0)); then
#day is 1,8,15,22,29 hour is 0 (we keep) use this space if you want to copy or something!
:
else
#Wrong day or hour
rm $file
fi
else if ((days < nowdays-7)); then
# more than one week
if ((10#$hour == 0)); then
#hour is zero se this space if you want to copy or something!
:
else
#Wrong hour
rm $file
fi
else
# less than one week (we keep) use this space if you want to copy or something!
:
fi fi fi


done


I have defined a month as 31 days always for checking if over 1 month. For once a week I pick days 1 8 15 22 and 29, so there is always the first day of the month. This also works on the back catalogue because it checks for midnight for each file.



The : lines are just place holders in case you want to put code there.



Give it a check before running it on everything, just in case there is an error!


[#27779] Thursday, November 11, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ameatoes

Total Points: 321
Total Questions: 106
Total Answers: 112

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
ameatoes questions
Tue, Aug 16, 22, 22:50, 2 Years ago
Fri, May 14, 21, 03:36, 3 Years ago
Sat, Oct 8, 22, 01:00, 2 Years ago
Fri, Feb 17, 23, 14:44, 1 Year ago
;