SKYCUBE.net

Solutions for Go, MySQL, PHP, Linux and more

Backup multiple folder (directories) in separate compressed files

Posted — Jun 30, 2016

Backup multiple folders (directories) in individual compressed files via a simple script and place them into a date-time based structure. This is a simple task and very useful for i.e. /home/ or /var/www/ directories.

Create a script file i.e. /root/folder_backup.sh and make it executable:

touch /root/folder_backup.sh
chmod u+x /root/folder_backup.sh

Now open the file and paste the below. Change the folders (directories) you like to be backup and the where you like the backups to be stored by changing the LOCALDIR and BACKUPBASE variable:

#!/bin/sh
################################################
# Simple script to backup multiple folders (directories) in separate
# compressed files. Good for /homes/* or /var/www/*
# @Author: Per Lasse Baasch (https://skycube.net)
# @Version: 2016-06-30
#############################################
### Local Base To Backup, NO TAILING SLASH!
LOCALDIR='/var/www'
### Backup Base Directory,  NO TAILING SLASH!
BACKUPBASE='/srv/backups'
CURRENTDATETIME=$(date +%Y%m%d_%H%M%S);
mkdir $BACKUPBASE'/'$CURRENTDATETIME;
for dir in $LOCALDIR/*/
do
  base=$(basename "$dir")
  tar --absolute-names -czf "${BACKUPBASE}/${CURRENTDATETIME}/${base}.tar.gz" "$dir"
done

Test the script by

/root/folder_backup.sh

If you now like to execute this nightly just add a crontab:

crontab -e

And add the following line(s):

# Backup folder nightly
0 0 * * * /root/folder_backup.sh > /dev/null 2>&1