Skip to content

Instantly share code, notes, and snippets.

@YannMjl
Created June 3, 2022 02:23
Show Gist options
  • Save YannMjl/8317a99ec8bdd14b5640e1b6e283ec14 to your computer and use it in GitHub Desktop.
Save YannMjl/8317a99ec8bdd14b5640e1b6e283ec14 to your computer and use it in GitHub Desktop.
#!/bin/bash
now=$(date)
BACKUPS_DIR="/location where my backup log files are stored"
# create log file
touch $BACKUPS_DIR/backup_delete.log
echo "Date: $now" > $BACKUPS_DIR/backup_delete.log
# declare static Array of file names
file_names=('backup_*.tgz' 'backup_file2*.log' 'log_file*.log')
# deletes files found in the backup directory (BACKUPS_DIR) but not deeper (-maxdepth 1)
# with the last modified time of over 30 days ago (-mtime +30) and a name which
# matches the pattern of the filename from the file_names array.
for filename in "${file_names[@]}";
do
echo $filename
# check if the backup files exit in the backup directory
if ls $BACKUPS_DIR/$filename &> /dev/null
then
echo "backup files exit"
# check if backup files older than 30 days exit than delete them
if find $BACKUPS_DIR -maxdepth 1 -mtime +30 -name $filename -ls &> /dev/null
then
# File exit. Now delete backups files that are older than 30 days
echo "The following backup file was deleted" >> $BACKUPS_DIR/backup_delete.log
find $BACKUPS_DIR -maxdepth 1 -mtime +30 -name $filename -ls >> $BACKUPS_DIR/backup_delete.log
# delete those files
find $BACKUPS_DIR -maxdepth 1 -mtime +30 -name $filename -delete
else
echo "There are no" $filename "files older than 30 days in" $BACKUPS_DIR &>> $BACKUPS_DIR/backup_delete.log
# send email notification
mail -s "Backup Logs" email@example.com < $BACKUPS_DIR/backup_delete.log
fi
else
echo "No" $filename "files found in" $BACKUPS_DIR >> $BACKUPS_DIR/backup_delete.log
# send email notification
mail -s "Backup Logs" email@example.com < $BACKUPS_DIR/backup_delete.log
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment