Tag Archives: tar

Bash script for complete system backup on external hard drive using tar

Some time ago I posted a script to backup Linux system to external drive using rsync. As the task this time was to create an archive of the whole system and the old backup files to be removed the script had to be changed a bit. Here is the version of it with the use of tar command. As before your external drive’s mount point has to be defined in fstab file.

And this is the script, it does not need much explanation:

 

#!/bin/bash

# Script to create full system archived backup to external USB drive.

# Specify the mount point, backup path and other stuff here (DO NOT end mount_point with a forward-slash).

mount_point=’/mnt/WD’
current_year=`date +%Y`
current_day=`date +’%Y-%m-%d_%H:%M:%S’`
backup_path=${mount_point}’/backup/’${current_year}
files_to_keep=2

echo “#####”
echo “”

# Check whether target volume is mounted, and mount it if not.

if ! mountpoint -q ${mount_point}/; then
   echo “Mounting the external USB drive.”
   echo “Mountpoint is ${mount_point}”
      if ! mount ${mount_point}; then
         echo “An error code was returned by mount command!”
         exit 5
      else echo “Mounted successfully.”
      fi
else echo “${mount_point} is already mounted.”;
fi

# Target volume **must** be mounted by this point.

if ! mountpoint -q ${mount_point}/; then
   echo “Mounting failed! Cannot run backup without backup volume!”
   exit 1
fi

echo “Preparing the archive using tar.”

mkdir –parents ${backup_path}/

tar czf ${backup_path}/${current_day}_backup.tar.gz –exclude=${backup_path}/${current_day}_backup.tar.gz –exclude=/dev/* –exclude=/mnt/* –exclude=/proc/* –exclude=/sys/* –exclude=/run/* –exclude=/media/* –exclude=/tmp/* –exclude=/lost+found /

# Delete old backup files

cd ${backup_path}/

rm -f `ls -t *_backup.tar.gz | awk “NR>$files_to_keep”`

cd /

# Dismounting target volume

if ! umount ${mount_point}; then
   echo “An error code was returned by command!”
   exit 5
else
echo “Dismounted successfully.”;
fi

 

And you are good to go! 🙂