Automated backup of Ubuntu user files and LVM configuration [Scheduled jobs series #1]

I’ve put together a short series on the jobs I have running on my NAS on a regular basis which I rely on to backup various config files or even the whole filesystem, or to monitor the health of my hard drives. Feel free to copy should you wish.

This script backs up & emails the following:

  • LVM config files – needed for recovering from some types of hard drive failures. These files can be used to recover from an accidental change (like deleting the wrong LV), LVM also keeps a backup copy of the most recent metadata in /etc/lvm/backup. These can be used to restore metadata to a replacement disk, or repair corrupted metadata. https://wiki.gentoo.org/wiki/LVM#Troubleshooting
  • Any user created scripts in the ~/scripts/* directory.

Okay, let’s create our backup script and open it to write contents…

mkdir -p ~/scripts/backuplvm
mkdir ~/scripts/backup_user_content 
nano ~/scripts/backup_user_content/backup_and_email.sh

Use the script below, but change the various parts of it to match your specific requirements (e.g. exactly what locations you want to backup), in particular the email address at the end which you use to send the confirmation to. You can also use a Pushbullet notification if you have set this up (see how to here).

#!/bin/sh
####################################
#
# Backup select files and email.
#
####################################

#Run LVM config backup
vgcfgbackup -f ~/scripts/backuplvm/lvmbackup-%s


#####################################

# What to backup. 
backup_files="~/scripts*"

# Where to backup to.
Mkdir -p ~/backups
dest="~/backups/"

# Create archive filename.
day=$(date +%Y%m%d)
hostname=$(hostname -s)
archive_file="$hostname-$day.tgz"

# delete previous backup files (optional - comment out if you want to keep them)
rm "$hostname"backup*.tar

# Print start status message.
echo "Backing up $backup_files to $dest$archive_file"
date
echo

# Backup the files using tar.
tar czf $dest$archive_file $backup_files

# Print end status message.
echo
echo "Backup finished"
date

#Email target file
mutt -s "Monthy NAS Backup" -a "$dest/$archive_file" - YOUR.EMAIL.ADDRESS < /dev/null

Now make this script executable…

chmod 775 ~/scripts/backup_user_content/backup_and_email.sh

To run the script on a regular basis (I run it on the first of every month), add the command to cron via Webmin or via command line using guide here.

Leave a Reply

(email optional)


Warning: Undefined array key "rerror" in /home/public/blog/wp-content/plugins/wp-recaptcha/recaptcha.php on line 291