Published December 29, 2017 by

Automatic take MySQL Database Backup Using CRONTAB

This article describes how to set up a cron job that automatically backs up a MySQL database to a file at specific time periods.

Suppose I want to take db backup every hours of everyday. So create a .sh file according to below script.


Step 1:


I created file in /root/backup.sh



#!/bin/bash
YEAR=`date +%Y`
MONTH=`date +%m`
DAY=`date +%d`
HOUR=`date +%H`
mkdir -p $YEAR/$MONTH/$DAY/$HOUR
mysqldump -u root -p12345 db_name > $YEAR/$MONTH/$DAY/$HOUR/backup_db.sql

Give execute permission to backup.sh 


# chmod +x /root/backup.sh

Step 2:

Create a cron job for executing this script to run every first minute of every hour.

# crontab -e

Type 


1 * * * * root /root/backup.sh

Save and Exit.

Now our system takes automatic take backup of database db_name and save to /root directory.