如何自动删除服务器上90天以上的MySQL备份文件
Hey there! Great job keeping that backup script running reliably for over 5 years—consistent backups are such a lifesaver. Adding automatic deletion of backups older than 90 days is simple, and we can integrate it directly into your existing script without breaking anything.
How It Works
We'll use the find command, which is perfect for locating and deleting files based on age. Here's the key command we'll add:
find ${dbprefix} -type f -name "*.sql.gz" -mtime +90 -delete
Let's break down what each part does:
${dbprefix}: Targets your backup directory so we only operate there-type f: Ensures we only delete files (not directories)-name "*.sql.gz": Restricts cleanup to your backup files—avoids accidentally deleting unrelated items-mtime +90: Matches files modified more than 90 days ago (note the+sign—without it, it would target files exactly 90 days old)-delete: Deletes the matched files (always test first without this flag!)
Modified Full Script
I've added the cleanup command at the end of your script, right after all backups finish. You could also add it at the start if you prefer to clean up before creating new backups—either works.
#!/bin/bash uname=XXXX upass=XXX dbprefix="/home2/XXX/DatabaseBackups" # Optional: Clean up old backups FIRST (uncomment if you prefer this order) # find ${dbprefix} -type f -name "*.sql.gz" -mtime +90 -delete # Run daily backups for db in $(echo -e "show schemas like \"XXXX%\";" | mysql -u $uname -p$upass -N) do wget -q -nv -P ${dbprefix} --http-user=${uname} --http-password=${upass} --auth-no-challenge http://localhost:2082/getsqlbackup/${db}.sql.gz done # Clean up backups older than 90 days (run AFTER backups complete) find ${dbprefix} -type f -name "*.sql.gz" -mtime +90 -delete
Critical Testing Tip
Before letting this run automatically, test the find command without the -delete flag to make sure it's targeting the right files:
find /home2/XXX/DatabaseBackups -type f -name "*.sql.gz" -mtime +90 -print
This will list all files that would be deleted. Double-check the list to confirm no important files are included—better safe than sorry!
Extra Safety Option
If you're nervous about deleting files directly, you can first move them to a temporary directory for manual review before deleting:
# Create a temp directory if it doesn't exist mkdir -p /tmp/old_mysql_backups # Move old backups there find ${dbprefix} -type f -name "*.sql.gz" -mtime +90 -exec mv {} /tmp/old_mysql_backups/ \;
After verifying the files are indeed safe to remove, you can delete the temp directory later.
内容的提问来源于stack exchange,提问作者JS7319

