backup/cleaner.sh
2024-08-08 05:50:15 +05:00

40 lines
1002 B
Bash

#!/bin/bash
EXPIRE_DAYS=14
SCAN_DIR=/backups
if [ "$(id -u)" != "0" ]; then
echo -e "\033[31mThis script requires superuser rights\033[0m"
exit 0
fi
trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT
set -e
export DEBIAN_FRONTEND=noninteractive
echo 'Cleaning old backups...'
FILES=$(find $SCAN_DIR -type f)
for file in $FILES;
do
timestamp=$(date -r "$file" +%Y%m%d)
echo "Processing $file file.."
date1yrs=$(date -d "$timestamp" +%Y)
date1days=$(date -d "$timestamp" +%j)
date2yrs=$(date +%Y)
date2days=$(date +%j)
diffYear=$((date2yrs - date1yrs))
diffYear2days=$((diffYear * 365))
diffDays=$((date2days - date1days))
DAYS=$((diffYear2days + diffDays))
if [ "$DAYS" -ge $EXPIRE_DAYS ]
then
echo "Deleting $file file..."
rm "$file"
fi
done
trap - EXIT
echo "All backups older than $EXPIRE_DAYS days are deleted."