Automate MySQL Backups with a Simple Shell Script and Cron
This guide walks you through creating a Linux shell script that uses mysqldump to back up a MySQL database, organizing old backups, setting execution permissions, and scheduling the process with cron for reliable, automated daily backups.
Shell scripts let you bundle a series of commands into a single executable file, making repetitive tasks like database backups easy to run on any Linux or UNIX system.
Prerequisites: basic knowledge of shell scripting, mysqldump , and crontab .
1. Create backup directories
# mkdir /backup # mkdir /oldbackup2. Write the backup script (backup.sh)
Use your favorite editor (e.g., vi) to create /backup/backup.sh and add the following commands:
#!/bin/bash
cd /backup
echo "You are In Backup Directory"
mv backup* /oldbackup
echo "Old Databases are Moved to oldbackup folder"
Now=$(date +"%d-%m-%Y--%H:%M:%S")
File=backup-$Now.sql
mysqldump -u user-name -p 'password' database-name > $File
echo "Your Database Backup Successfully Completed"3. Make the script executable
# chmod +x /backup/backup.sh4. Run the script manually
# ./backup.shOn first run you may see a “no such file” warning because the old‑backup folder is empty; running the script again will work without issues.
5. Schedule automatic backups with cron
Edit the crontab: # crontab -e Add a line to run the script every day at 13:00 (1 PM): 0 13 * * * /backup/backup.sh Refer to the crontab manual for more scheduling options.
This basic script provides a foundation you can extend for more complex backup strategies.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
