Operations 4 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Automate MySQL Backups with a Simple Shell Script and Cron

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 .

Backup script illustration
Backup script illustration

1. Create backup directories

# mkdir /backup
# mkdir /oldbackup

2. 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.sh

4. Run the script manually

# ./backup.sh

On 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Automationcronmysql backup
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.