backup/cleaner.sh

40 lines
1002 B
Bash
Raw Normal View History

2024-07-11 21:18:02 +05:00
#!/bin/bash
EXPIRE_DAYS=14
SCAN_DIR=/backups
if [ "$(id -u)" != "0" ]; then
2024-08-08 05:50:15 +05:00
echo -e "\033[31mThis script requires superuser rights\033[0m"
2024-07-11 21:18:02 +05:00
exit 0
fi
trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT
set -e
export DEBIAN_FRONTEND=noninteractive
2024-08-08 05:50:15 +05:00
echo 'Cleaning old backups...'
2024-07-11 21:18:02 +05:00
FILES=$(find $SCAN_DIR -type f)
for file in $FILES;
do
2024-08-08 05:50:15 +05:00
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))
2024-07-11 21:18:02 +05:00
if [ "$DAYS" -ge $EXPIRE_DAYS ]
then
2024-08-08 05:50:15 +05:00
echo "Deleting $file file..."
rm "$file"
2024-07-11 21:18:02 +05:00
fi
done
trap - EXIT
echo "All backups older than $EXPIRE_DAYS days are deleted."