Learn about Centmin Mod LEMP Stack today
Register Now

Backup File Bash Script

Discussion in 'System Administration' started by Jimmy, Dec 3, 2015.

Tags:
  1. Jimmy

    Jimmy Premium Member Premium Member

    1,165
    256
    83
    Oct 24, 2015
    East Coast USA
    Ratings:
    +626
    Local Time:
    7:28 PM
    1.13.x
    MariaDB 10.1.x
    I'm trying to create a bash script to backup the databases for three sites. It got a little involved, so I thought I would throw it up here to make sure I have it setup correct. Here is what I have:

    Create / Add the Backup Script
    Code:
    nano /root/tools/backup-databases.sh
    Bash Script
    Code:
    #!/bin/bash
    #Purpose = Database Backups
    TIME=`date +%b-%d-%y`
    # MYSQL User which will probably be root
    MYSQLUSER=user
    # MYSQL Databases on server
    MYSQLDBASE1=databasename1
    MYSQLDBASE2=databasename2
    MYSQLDBASE3=databasename3
    # MYSQL Database Filenames
    FILENAME1=$MYSQLDBASE1-$TIME-backup.sql
    FILENAME2=$MYSQLDBASE2-$TIME-backup.sql
    FILENAME3=$MYSQLDBASE3-$TIME-backup.sql
    # Directories
    DESDIR=/root/backups/databases
    # Time based backup directory
    DBASEBACKUPNAME=databasesBackup-$TIME
    # Make time based directory to hold sql files
    mkdir /root/backups/databases/$DBASEBACKUPNAME
    TIMETEMDIR=/root/backups/databases/$DBASEBACKUPNAME
    # Dump Databases to /root/backups/databases/databasesBackup-$TIME folder
    mysqldump -u $MYSQLUSER -p $MYSQLDBASE1 > $TIMETEMDIR/$FILENAME1
    mysqldump -u $MYSQLUSER -p $MYSQLDBASE2 > $TIMETEMDIR/$FILENAME2
    mysqldump -u $MYSQLUSER -p $MYSQLDBASE3 > $TIMETEMDIR/$FILENAME3
    # Tar directory with database backups
    tar -cazf $TIMETEMDIR/$DBASEBACKUPNAME.tar.gz $DESDIR
    # Delete folder with SQL file backups
    rm -r $TIMETEMDIR
    mail -s "CENTMIN MOD Database Backup $TIME" mail@example.com <<< "CENTMIN MOD domain database backup has been completed."
    Modify the Permissions on the File
    Code:
    chmod +x /root/tools/backup-databases.sh
    Access the Cron Interface
    Code:
    crontab -e
    Cron Job (will run everyday at 11PM)
    Code:
    01 23 * * * /root/tools/backup-databases.sh 2>/dev/null
     
  2. Jimmy

    Jimmy Premium Member Premium Member

    1,165
    256
    83
    Oct 24, 2015
    East Coast USA
    Ratings:
    +626
    Local Time:
    7:28 PM
    1.13.x
    MariaDB 10.1.x
    Thanks for the info! I'll read those over!