Simple Backup Script

Simple Backup Script

A simple backup script which backs up the OS directories of a Linux system remotely. root SSH keys must be configured between systems. SSHFS must be installed and the mailer must be running and configured to send mail. The script mounts the root directory of another system, in read-only mode, via SSHFS. It finds remote incremental files of OS directories only, which are one day old, then creates a tarball in the /dump/os/ directory; else a full backup every Friday. Next, deletes backup files more than 2 weeks old; all scheduled via cron. Last, it sends an email of the success or failure.

#!/bin/bash

# Backup the OS directories only, daily.
# Full or inc backups using sshfs, find, tar.
# Email success or failure.
# Delete tarballs more than 14 days old.
# Schedule via cron.
# by Ramses Soto-Navarro <ramses@sotosystems.com> 2/26/2025

export S=$1
export D=/mnt/$1-$RANDOM
export D2=/dump/os
export DATE=$(date +%Y%m%d%H%M%S-$RANDOM)
export FILE=/dump/os/backup-$1-$DATE
export MAIL=ramses@sotosystems.com

export SYNTAX="$BASH_SOURCE <hostname> <-f|-i|-d>"

f_mount () {
mkdir -p $D
sshfs -o ro $S:/ $D
cd $D
}

f_umount () { 
cd
umount $D 
rm -rf $D
#2&>1
}

f_full () {
#f_umount
f_mount
export FULLFILE=$FILE-FULL.tgz
tar zcf $FULLFILE  bin etc lib root sbin usr boot home lib64 opt shell_scripts tmp var 
export RET=$(echo $?)
f_umount
f_mail
}

f_inc () {
#f_umount
f_mount
export FULLFILE=$FILE-INC.tgz
tar zcf $FULLFILE `find bin etc lib root sbin usr boot home lib64 opt shell_scripts tmp var -type f -mtime 1`
export RET=$(echo $?)
export SIZE=$(ls -sh $FULLFILE | awk '{print $1}')
f_umount
f_mail
}

f_del () {
find /dump/os/ -type f -mtime +14 -delete
}

f_mail () {
if [ $RET == 0 ]; then
	export MSG="Sussess backup: $FULLFILE" 
else
	export MSG="Failed backup: $FULLFILE"
fi
echo "$MSG - $SIZE" | mail -s "$MSG - $SIZE" "$MAIL"
}

case $2 in
	f|-f)	f_full ;;
	i|-i)	f_inc ;;
	d|-d)	f_del ;;
	*)	echo $SYNTAX ;;
esac

Schedule the backup via cron:

# Full backup OS directories Friday 6PM.
0 18 * * 5 /root/bin/backup-os.sh linuxserver1 -f

# Incremental backup OS directories Mon-Thur 6PM. 
0 18 * * 1-4 /root/bin/backup-os.sh linuxserver1 -i

# Delete backup files older than 2 weeks Sunday 6PM.
0 18 * * 0 /root/bin/backup-os.sh -d