• Home
  • About
    • Richie's Blog photo

      Richie's Blog

      Science, data, biology, digital health, programming, tech

    • Learn More
    • Twitter
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Using a bash script for backing up MySQL databases

16 May 2016

Reading time ~1 minute

Setting up batch jobs for regular housekeeping tasks can be easily handled using shell scripts. This is an example of some code that could be used for backing up a number of databases with a single script, and recording those backups in logfiles.

#!/bin/bash

user="username"
pass="password"

# Define backup directory
backup_dir="/Users/username/path/to/backup/directory"

# Define log directory
log_dir="/Users/username/path/to/logs/directory"

# Define databases to backup
myarray=("database1" "database2" "database3")

# Loop through all databases
for database in "${myarray[@]}"
do

    # Get timestamp
    now=$(date +"%Y%m%d%H%M%S")

    # Define backup location
    backup_file="${backup_dir}/${database}_${now}.sql"

    # Print out name for backup file (for simple monitoring)
    echo "${database}_${now}.sql"

    # Define logfile for that database
    logfile="${log_dir}/${database}.txt"

    # Concat info on mysqldump starting to the logfile
    echo "mysqldump started at $now" >> "$logfile"

    # Perform backup using mysqldump
    mysqldump --user="$user" --password="$pass" --default-character-set=utf8 "$database" > "$backup_file"

    # Update timestamp for logfile 
    now=$(date +"%Y%m%d%H%M%S")

    # Log completion of database backup in logfile
    echo "mysqldump finished at $now" >> "$logfile"
    echo "*****************" >> "$logfile"

done

# Exit the shell script
exit 0

In order to run periodically, which can be recommended, but depends on the details of each database and type of data being stored, this script can be set as a cronjob by editing the crontab (NB script needs to be executable in order for the crontab to be able to run it).

$ chmod +x /Users/username/Scripts/backup_databases.sh

Open crontab for editing:

$ crontab -e

Example: set script to run nightly at one minute past 4 every morning.

01 04 * * * /Users/username/Scripts/backup_databases.sh


Like Tweet +1