Reputation: 1
I'm very new in bash script and need to write this code.
The purpose of this code is to delete older backups depending on how old they are. The folders name is the date they were made. I think I commented everything, so the idea should be easy to get.
#!/bin/sh
#delte backups automatically
cd backup/backup_collection #make sure to be in the right directory
todate=$(date +”%Y-%m-%d”) #today
count_back=$(ls -l | grep "^d" | wc -l) #counts the number of folders in the current directory
back_names=( $( ls . ) ) #array with all filenames
for ((i=0; i<count_back; i++ ))
do
back_days[i]=$(( (todate +%s - todate +%s -d ${back_names[i]}) /86400 )) #this number tells us how many days ago this backup was
done
#the array with the days is already sorted from small to big
y=$(((${back_days[count_back-1]} + 2) / 7)) #y is the newest date, how many weeks ago
for ((i=count_back-2; i>=0; i—- ))
do
x=$(((${back_days[i]} + 2) / 7)) #how many weeks ago is the i-th entry
if [ x<8 ] || [ [ x>=8 ] && [ x<=26 ] && [ y-x>=2 ] ] || [ [ x>=26 ] && [ x<52 ] && [ y-x>=4 ] ] || [ [ x>=52 ] && [ y-x>=8 ] ]
then
y=$x
else
rmdir backup/backup_collection/${back_names[i]} #we remove the specific folder
fi
done
The code does not work yet. For example this line is not correct I think.
back_days[i]=$(( (todate +%s - todate +%s -d ${back_names[i]}) /86400 ))
I tried very much. Maybe someone can help me. I would appreciate it!
Upvotes: 0
Views: 80
Reputation: 27
you can use the find command
find $RAIZ/ -name "*.gz" -atime +2 -type f -print -exec rm {} \;
where $ RAIZ is the directory where they are. atime is the antiquity time in days and * .gz all extension files .gz Maybe it's not exactly what you need, but it's a start
Upvotes: 0
Reputation: 912
What I'm using is something like that
MAXKEEP=30
ZIPPER_EXT="gz"
find $LOG_DIR -type f -name "*.$ZIPPER_EXT" -mtime +$MAXKEEP -exec rm -rf {} \;
LOG_DIR is self-explaining, and I do compress (in other part of the script) my files after a certain amount of time so I'm looking for the compressed files only. So, that line do erase compressed file after 30 days. But that can be modified easily to suits your need I think.
Upvotes: 1