Please read the following manual carefully. I disclaim any liability for data loss or other errors.



A few days ago I’ve had the idea to improve the backup script for my Linux Gentoo system which has been very basic but working for a long time. My idea has been to write a backup script which considers the following thoughts:

  • Do some basic checks for the backup directory - existing directories, …
  • Backup only the relevant data and leave out unnecessary stuff to keep the backup as small as possible.
  • Delete all backups which are older than x days.



The result is no rocket science but something I would like to share with you. The only parameters which need to be configured are the both on the top of the script: BACKUPDIR and HOLDBACKTIME. You can use your prefered tool like Cron to schedule your backups.


#!/bin/bash

BACKUPDIR=”/mnt/sys-data/backup”
# Value in days - 1. E. g. keep backup for 14 days –> 13
HOLDBACKTIME=13
SOURCEDIR=”/”

CURRENT_DATE=$(date +”%Y-%m-%d”)
DESTDIR=”$BACKUPDIR/$CURRENT_DATE”
DESTDIR_TMP=”$DESTDIR/tmp”
TAR_PATH=”$DESTDIR/backup_$CURRENT_DATE.tar.gz”

echo “Start of backup process …”

# Create needed DIRs
echo “Create Backup directories”
if [ ! -d "$DESTDIR" ]; then
mkdir $DESTDIR
fi

if [ -d "$DESTDIR_TMP" ]; then
rm -r $DESTDIR_TMP
fi
mkdir $DESTDIR_TMP

# Backup the system to the temp DIR
echo “Start backup”
rsync -autl –exclude=/mnt –exclude=/dev –exclude=/sys –exclude=proc –exclude=/var/tmp –exclude=/usr/portage/distfiles –exclude=/usr/portage/packages$
echo “End of backup”

# Comprimize the backup to an archive
echo “Create archive from backup”
tar -czf $TAR_PATH $DESTDIR_TMP
echo “Delete backup temp directory”
rm -r $DESTDIR_TMP

# Cleanup older backups but keep at least the last one
echo “Delete all backups which are older than x days”
find $BACKUPDIR -mindepth 1 -maxdepth 1 -type d -mtime +$HOLDBACKTIME -exec rm -r {} \;

echo “… End of backup process”

NOTE: Please make sure that your backup directory is outside of the actual backup range (s. SOURCEDIR) or add this directory to the exlude list in line .

Hinterlasse einen Kommentar