Automate MySQL Backups with Bash Scripts and Cron Jobs
This guide explains why database backups are essential, walks through preparing storage, creating a Bash script to dump and compress MySQL data, granting execution rights, scheduling the script with crontab, and verifying successful automated backups on Linux systems.
Why Backups Matter
Backing up data is the foundation of disaster recovery; it protects against accidental deletions or system failures by copying databases to separate storage media.
Choosing a Storage Medium
Optical disc Magnetic tape Hard disk Disk array DAS (Direct‑Attached Storage) NAS (Network‑Attached Storage) SAN (Storage Area Network) Cloud storage
The tutorial focuses on using a local hard‑disk as the backup target.
Step‑by‑Step Backup Setup
1. Check Available Disk Space
Ensure the destination disk has enough free space to avoid backup failures.
# df -h2. Create a Backup Directory
Choose a directory on a disk with sufficient space, e.g., /home/backup.
cd /home
mkdir backup
cd backup3. Write the Backup Shell Script
Replace DatabaseName with the actual MySQL database name, and adjust the username/password.
#!/bin/bash
mysqldump -uusername -ppassword DatabaseName > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sqlTo compress the dump directly:
#!/bin/bash
mysqldump -uusername -ppassword DatabaseName | gzip > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sql.gzNote: Replace username, password, and DatabaseName with real values.
4. Make the Script Executable
chmod u+x bkDatabaseName.shRun it once to verify it works:
./bkDatabaseName.sh5. Schedule the Backup with Cron
First, ensure crontab is installed (install via yum install crontabs on CentOS if missing).
Edit the crontab file: crontab -e Add the following line to run the script every minute (adjust the schedule as needed): */1 * * * * /home/backup/bkDatabaseName.sh This entry means the script executes once per minute.
6. Verify the Cron Job
After a few minutes, list the backup directory to see generated files, or monitor the cron log: # tail -f /var/log/cron Typical log entries show the cron daemon starting and finishing the scheduled task.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
