MySQL Database Backup with Shell Script and Cron
This guide explains how to set up automated MySQL database backups using a shell script that runs mysqldump (optionally compressed), stores the files on a local disk, makes the script executable, and schedules it with a cron job after verifying disk space and cron availability.
Backup is the foundation of disaster recovery, copying data to other storage media to prevent loss.
What is backup?
Backup copies all or part of data from the primary host to another storage medium.
Why backup?
Database is critical for many systems; regular backups are essential.
Storage media
CD, Tape, Hard Disk, Disk Array, DAS, NAS, SAN, Cloud Storage
The guide focuses on using a local disk and cron jobs to automate MySQL backups.
1. Check disk space
# df -hFilesystem2. Create backup directory
cd /home
mkdir backup
cd backup3. Create backup script
vi bkDatabaseName.shInsert the following content (replace placeholders with actual values):
#!/bin/bash
mysqldump -uusername -ppassword DatabaseName > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sqlCompressed version:
#!/bin/bash
mysqldump -uusername -ppassword DatabaseName | gzip > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sql.gz4. Make script executable
chmod u+x bkDatabaseName.shRun to verify:
./bkDatabaseName.sh5. Add cron job
Check if crontab is installed:
# crontab
-bash: crontab: command not foundInstall if necessary, then edit:
crontab -eAdd the line to run every minute:
*/1 * * * * /home/backup/bkDatabaseName.sh6. Test execution
Monitor logs:
# tail -f /var/log/cronSample output shows the job being triggered.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.