Categories: MySQL

Shell script to backup all mysql databases and upload via FTP

You have learnt how to backup MySQL databases using the mysql dump in my previous post. You may want to setup a cron job which will back up MySQL databases and upload them on a remote server using FTP. The following shell script will help you to achieve this.

#!/bin/bash

#Variables
FILENAME=/loc/to/file/$(date +%Y%m%d).sql
FILENAMEREMOTE=/loc/to/file/$(date +%Y%m%d).sql
FTPHOSTNAME=”ip and port”
FTPUSERNAME=””
FTPPASSWORD=””
SQLUSERNAME=””
SQLPASSWORD=””
MESSAGE=”Databases Backup Successful”

#SQL BACK UP
mysqldump -u $SQLUSERNAME –password=$SQLPASSWORD –all-databases > $FILENAME

#Upload file to FTP now
ftp -inv $FTPHOSTNAME << EOF
user $FTPUSERNAME $FTPPASSWORD
put $FILENAME $FILENAMEREMOTE
ls
bye
EOF

#Delete SQL file after backup.
rm -Rf $FILENAME

Save the above script and assign it a name which will be easy to identify. I will name it as mysqlbackup.sh. Assign it appropriate permission.

chmod +x mysqlbackup.sh

You can save the script in any location of your choice. I will store it in /scripts directory.

Now set the cron job to execute the script at your preferred schedule.

I use this command to run it every morning at 5 am.

0 4 * * * /scripts/mysqlbackup.sh

Nitesh Shah

View Comments

  • Hello Nitesh,

    We can also use command "tar -cvf" to compress DB backup which will reduce size of the backup file.

Share
Published by
Nitesh Shah

Recent Posts

How to setup first Azure Virtual Machine?

Setting up your first Azure Virtual Machine can be done by following these steps: Create…

1 year ago

How to setup Amazon Cloudfront and S3 to serve static resources

Amazon CloudFront is a content delivery network (CDN) that helps you serve static content such…

1 year ago

Step-By-Step Guide To Setting Up An AWS Application Load Balancer

Step-By-Step Guide To Setting Up An AWS Application Load Balancer Are you looking for a…

1 year ago

How to restore MySQL database from .frm and .ibd files?

MySQL databases often get corrupted due to issues like hardware failure, file system failure etc.…

4 years ago

SQL Server Replication

SQL Server Replication is the process of copying databases from one node to another to…

5 years ago

101 System Admin Tools to make life easy

Here are 101 System Admin tools which make System Admins' life easy.

7 years ago

This website uses cookies.