Skip to content

Instantly share code, notes, and snippets.

@khasky
Last active February 21, 2021 19:25
Show Gist options
  • Save khasky/da437b3207928ab36937bd885392a167 to your computer and use it in GitHub Desktop.
Save khasky/da437b3207928ab36937bd885392a167 to your computer and use it in GitHub Desktop.
Bash MySQL backup to tar.gz for single database
#!/bin/bash
MYSQL_USER=root
MYSQL_PASS=root
MYSQL_DB=test
BACKUP_DIR=/var/local/backup
LOGS_DIR=/var/log
# Equals to 3 last days
MAX_OLD_BACKUPS_DAYS=1
DATE=`date '+%Y-%m-%d_%H-%M-%S'`
mkdir ${BACKUP_DIR}
cd ${BACKUP_DIR}
echo "Deleting old backups and logs from $BACKUP_DIR & $LOGS_DIR"
# https://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/
#find ${LOGS_DIR} -type f \( -name "*.gz" -o -name "*.1*" \) -exec rm '{}' \;
find ${BACKUP_DIR} -mtime +${MAX_OLD_BACKUPS_DAYS} -exec rm '{}' \;
echo "Backup database to $BACKUP_DIR"
mysqldump -u ${MYSQL_USER} -p${MYSQL_PASS} ${MYSQL_DB} > ${MYSQL_DB}.sql
tar -czf ${DATE}_mysql.tar.gz ${MYSQL_DB}.sql
rm -rf ${MYSQL_DB}.sql
echo "Backup files to $BACKUP_DIR"
tar -czf ${DATE}_khasky_com.tar.gz /var/www/khasky.com/public_html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment