Skip to content
Fuzail Ahmed edited this page Sep 19, 2018 · 2 revisions

Database Backup Bash(Mysql)

Bin folder configuration(if not present at ~/ (home directory))

1 - create bin director in the ~/bin

2 - edit .bashrc file in ~/.bashrc and add following line in it

1 2 export PATH="$PATH:$HOME/bin" source .bashrc Above command will make your bin folder as accessible throughout the system.

File Creation

1 - create file or command in the bin directory and give it execute permission

1 2 touch get-projectname_backup chmod u+x get-projectname_backup

Install Git

Git Configuration

1 - Create folder e.g XYZ and go to XYZ folder

2 - Now initialize the git with

git init

3 - add a remote repository

3 - Add all the changes to staging with

git add .

4 - Add commit to the staged changes by

git commit -m 'message'

5 - If you want to store the password for the future changes

git config credential.helper store git push -u origin master

Setup Mysqldump credentials

cd ~/ touch .my.cnf nano .my.cnf #start writing in the file [mysqldump] user=USER_NAME password=USER_PASSWORD

Actual Script

!/bin/bash

Begin Push changes function

push_changes(){ full_date=$(date +"%Y-%d-%m %H:%M") current_path=$(pwd) cd $backup_path

    # Check current Git status and update
    git status
    git pull origin HEAD
    echo  "$full_date - Git status checking done." >> $logfile

    # Add to Git and commit
    git add -A
    git commit -m "Automatic backup - $full_date"
    git push origin HEAD
    echo  "$full_date - The changes are successfully pushed to the repository." >> $logfile
    cd $current_path

}

End Push changes function

Begin Variable Sections

logfile="/home/company_name/backups/project_name/database_logs/backuplogs.log" backup_path="/home/company_name/backups/project_name/database_backup" project_name="project_name" database_name="database_username"

End Variable Sections

Begin Backup script

echo "date +%Hh%Mm%Ss - Varibale declearation done and script started successfully." >> $logfile

echo "date +%Hh%Mm%Ss - MySql backup creation for $project_name is started." >> $logfile mysqldump $database_name > $backup_path/$project_name'_'date +%Y%m%d%H-%Hh%Mm%Ss.sql wait echo "date +%Hh%Mm%Ss - MySql backup creation for $project_name is completed." >> $logfile

echo "date +%Hh%Mm%Ss - Task for database backup is completed successfully." >> $logfile push_changes

End Backup script