Skip to main content

Scripting Incremental Backups Using Tar

By April 4, 2018September 12th, 2022No Comments

Incremental Backups Using TarIn the last tutorial we saw how we could streamline backup using incremental backups. This is often likely to happen each day and we can help the process by scripting incremental backups using tar. In this tutorial we look at creating a BASH shell script to allow for control of the backup.

Scripting Incremental Backups Using Tar

If we are to run backups regularly, we probaly want to automate them with a script. In this way they can run and run reliably out of hours. Scheduling the script with a utility such as cron and running the script at 22:00 each working day.

We need to make sure that on Monday we rename the old meta file to ensure a new meta file is used each week. We also like to name the archive after the day name, similar to the example we used earlier. We can extract the current day name using the command date.

$ date +%a

Today is Wedenesday is you have not worked it out 🙂

If we were to backup the same directory that we looked at in the main example, the script would look like this:

 #We can work out if the day of the week with date +%a Mon Tue Wed Thu Fri Sat Sun
 DAY=$(date +%a)
 #If it is Monday we need to make sure that we start with a new snar file to ensure full #backup
 #If the snar file is there it is renamed with a date extension of the previous Monday
 if [ $DAY = 'Mon' ]
    test -e ~/$SNAR && mv $SNAR ${SNAR}.$(date --date '7 days ago' +%F)
 tar -czg ~/$SNAR -f $TAR ~/$FILE

For ease of expansion of the tilde for the home directory and brevity of the command I have used the short options in the script with tar. The option -g is the same as –listed-incremental and the -f is the same as –file. The option -z compresses the archive and is the same as –gzip. The video now follows: