Skip to main content

Bash Shell script for backing up database and copying it to remote location.

#!/bin/bash

# THIS VERSION WILL ASK YOU FOR THE DATABASE NAME AND WHERE TO SAVE IT LOCALLY

function show_usage {
        echo "Usage: $0 database-name save-directory"
        exit 1
}

#Need two parameters
if [ $# -ne 2 ]; then
        echo "Two parameters required"
        show_usage;
fi

#Second parameter must be a valid directory
if [ ! -d $2 ]; then
        echo "Save directory (parameter 2) is invalid"
        show_usage
fi

database=$1
save_dir=$2
file_name="${database}-`date +%Y%m%d%H%M`.sql.gz"

mysqldump -u USER -pPASSWORD ${database} | gzip > ${save_dir}/${file_name}

if [ -e ${save_dir}/${file_name} ]; then
        echo "Local backup created"
fi

if scp ${save_dir}/${file_name} user@ip-or-location.com:~/BKUP
then
        echo "File copied to remote server successfuly"
fi

# ------------------------------

#!/bin/bash

# THIS VERSION WILL SAVE THE MYSQL DUMP TO THE LOCATION OF THE SCRIPT RUNNING IT

file_name="DATABASE_NAME-`date +%Y%m%d%H%M`.sql.gz"
script_dir="$( cd "$( dirname "$0" )" && pwd )"

#Create Local MySQL Dump
mysqldump -u USER -pPASSWORD DATABASE_NAME | gzip > ${script_dir}/${file_name}

if [ -e ${script_dir}/${file_name} ]; then
        echo "Local backup created"
fi

#Copy that file to remote location. Assumes SSH-key setup.
if scp ${script_dir}/${file_name} user@ip-or-location.com:/path/on/remote/server
then
        echo "File copied to remote server successfully"
fi