You can write a shell script to automatically back up the MySQL database. Here is a sample script that will:
- Backup the specified database (or all databases).
- Name the backup file by date to prevent overwriting.
- Automatically delete old backups from N days ago to save space.
Example: MySQL Backup Shell Script
#!/bin/bash #Configuration sectionBACKUP_DIR="/backup/mysql" # Backup and store directoryMYSQL_USER="root" # MySQL UsernameMYSQL_PASSWORD="yourpassword" # MySQL PasswordMYSQL_HOST="localhost" # MySQL Server AddressDATABASE_NAME="your_database" # Backup database name. To back up all databases, change it to --all-databasesRETENTION_DAYS=7 # The number of days left, automatically delete old backups # Get the current dateDATE=$(date +"%Y-%m-%d_%H-%M-%S") # Backup file nameBACKUP_FILE="$BACKUP_DIR/${DATABASE_NAME}_$" # Make sure the backup directory existsmkdir -p "$BACKUP_DIR" # Perform a backupmysqldump -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DATABASE_NAME" | gzip > "$BACKUP_FILE" # Check whether the backup is successfulif [ $? -eq 0 ]; then echo "MySQL Successful backup: $BACKUP_FILE" else echo "MySQL Backup failed!" exit 1 fi # Delete old backups N days agofind "$BACKUP_DIR" -type f -name "${DATABASE_NAME}_*." -mtime +$RETENTION_DAYS -exec rm {} \; echo "Cleaned old backup $RETENTION_DAYS days ago"
How to use
Copy the scriptGo to a Linux server, such as/backup/mysql_backup.sh
。
Modify script parameters(Database name, user name, password, etc.).
Grant execution permissions:
chmod +x /backup/mysql_backup.sh
Run the test manually:
/backup/mysql_backup.sh
Set up timing tasks, automatic backup at 2 a.m. every day:
crontab -e
Add to:
0 2 * * * /backup/mysql_backup.sh >> /backup/ 2>&1
This way, your MySQL database can be automatically backed up and cleaned up old backups every day to ensure data security!
This is the end of this article about the implementation of MySQL backup shell scripts. For more related contents of MySQL backup shell scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!