This Script was designed to backup a database onto a backup-server that (only) provides SMB-Shares.
If there are already more than $CYCLE files present within the destination directory, the oldest file will be overwritten.
You might get the impression that I am abusing my blog to host scripts.
Well, you’re right 😉
There you go:
#!/bin/sh # This script backs up a db with adjustable cycles BAKPATH='/mnt/backup' ## The Path to store the backups in SMBPATH='//10.10.10.10/backup' ## Path to the smb-share to store the backup in SMBUSER='user' ## User to login with SMBPASSWD='' ## Password to use for smb-auth. in base64 encoding CYCLE=7 ## Number of backup-files in one cycle, the oldest backup will be overwritten SUFFIX='_backup.sql' ## The suffix of the filename MYSQL_ROOTPW='' ## MySQL-Password for root in base64 encoding MYSQL_DB='somedb' ## The database to be backed up ;) LOGFILE='/var/log/backups' ## Where shall i write logs to? ### Mount the SMB-share to BAKPATH mount -t smbfs $SMBPATH $BAKPATH -o username=$SMBUSER,password=$( echo $SMBPASSWD | openssl enc -base64 -d ) ### Is it mounted correctly? MOUNTS=$( mount | grep $BAKPATH | wc -l ) if [ $MOUNTS -eq 0 ] ; then echo $(date)" Couldn't map SMB-share to my local FS! Exiting, no Backup created" >> $LOGFILE; if [ ! -d $BAKPATH ]; then echo $(date)" The specified BAKPATH doesn't exist!" >> $LOGFILE; fi else echo $(date)" SMB-share $SMBPATH mapped successfully to $BAKPATH!" >> $LOGFILE; ### Get the number of files in our BAKPATH NUMFILES=$(ls -1 $BAKPATH | wc -l) ### While the number of backups is >= $CYCLE while [ $NUMFILES -ge $CYCLE ]; do ### Get the oldest backup; delete it and do some output/logging OLDESTFILE=$( ls -t1 $BAKPATH | tail -n 1 ) OLDESTABSFILE=$BAKPATH"/"$OLDESTFILE rm $OLDESTABSFILE if [ ! -f $OLDESTABSFILE ]; then NUMFILES=`expr $NUMFILES - 1` echo $(date)" Deleted Backup $OLDESTABSFILE to make space ;)" >> $LOGFILE fi done ### Now create the backup FILE=$(date +%Y%m%d)"_"$(date +%H%M%S)$SUFFIX ABSFILE=$BAKPATH"/"$FILE mysqldump --user=root --password=$( echo $MYSQL_ROOTPW | openssl enc -base64 -d ) $MYSQL_DB > $ABSFILE tar -czf $ABSFILE.tar.gz $ABSFILE rm $ABSFILE ### Do some logging if [ -f $ABSFILE.tar.gz ]; then echo $(date)" Backup '$ABSFILE' successfully created" >> $LOGFILE; else echo $(date)" Couldn't create the backup!" >> $LOGFILE; fi umount $BAKPATH fi |