Skip to content

Instantly share code, notes, and snippets.

@jabranr
Last active June 6, 2021 14:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jabranr/d4939b2b48fdcadc74765a3ed04d8157 to your computer and use it in GitHub Desktop.
Save jabranr/d4939b2b48fdcadc74765a3ed04d8157 to your computer and use it in GitHub Desktop.
Automatic MySQL dump and backup to Git repo cron job
#!/bin/sh
#
# @author: Jabran Rafique <hello@jabran.me>
# @link: http://jabran.me/articles/automatic-database-backup-using-git-hosting/
# Set variables
FULLDATE = $(date +"%Y-%d-%m %H:%M")
NOW = $(date +"%Y-%m-%d-%H-%M")
MYSQL_DUMP = `which mysqldump`
GIT = `which git`
DB_NAME = "foo"
CRON_USER = "bar"
TEMP_BACKUP = "latest_backup.sql"
BACKUP_DIR = $(date +"%Y/%m")
# Check current Git status and update
${GIT} status
${GIT} pull origin HEAD
# Dump database
${MYSQL_DUMP} -u "$CRON_USER" $DB_NAME > $TEMP_BACKUP &
wait
# Make backup directory if not exists (format: {year}/{month}/)
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p $BACKUP_DIR
fi
# Compress SQL dump
tar -cvzf $BACKUP_DIR/$DB_NAME-$NOW-sql.tar.gz $TEMP_BACKUP
# Remove original SQL dump
rm -f $TEMP_BACKUP
# Add to Git and commit
${GIT} add -A
${GIT} commit -m "Automatic backup - $FULLDATE"
${GIT} push origin HEAD
@ppazos
Copy link

ppazos commented Nov 26, 2020

how is the git user configured?

I guess CRON_USER is the DB_USER.

@jabranr
Copy link
Author

jabranr commented Nov 27, 2020

@ppazos Git is assumed configured on the server. About CRON_USER, see section Setup a cron user in the article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment