How to Schedule a Backup of All Websites Hosted on Ubuntu

    Posted in Linux Servers on Nov 15, 2018

    Step 1: Create the Backup Script

    The first thing we need to do is create a simple backup script that will backup websites located in /var/www. The script will change into the directory and then loop through archiving each folder into /backups/www. It will also be able to cleanup backups older than X days.

    Create a folder to store your backup script in. I suggest /scripts for this example:

    sudo mkdir /scripts

    Create a file called inside the scripts folder:

    sudo vim /scripts/

    Add the following code to the file and save it:

    DAYS_TO_KEEP=7    # 0 to keep forever
    # Create the backup folder
    if [ ! -d $BACKUP_PATH ]; then
    mkdir -p $BACKUP_PATH
    # change into the web root directory
    cd "$WWW_PATH"
    if [ "$(pwd)" != "$WWW_PATH" ] ; then
    echo "Failed to change directory to root of web path"
    for website in * ; do
    if [[ -d $website && ! -L "$website" ]]; then
    echo "Found website folder: $website"
    date=$(date -I)
    tar -cvpzf $BACKUP_PATH/$date-$website.tar.gz $website
    # Delete old backups
    if [ "$DAYS_TO_KEEP" -gt 0 ] ; then
    echo "Deleting backups older than $DAYS_TO_KEEP days"
    find $BACKUP_PATH/* -mtime +$DAYS_TO_KEEP -exec rm {} \;

    You will notice 3 configurable options at the beginning of this script. If you are running the script on Ubuntu 16.04, you shouldn’t need to edit anything. However, you may want to change the backup location and the number of days worth of backups to keep.

    Once you have modified the options, make the script executable with the following command:

    sudo chmod +x

    You can now test the backup script by running:

    sudo ./

    After running the script you should see the sites have all been backed up to /backups/www. See below:

    Backup Result

    Step 2: Create the Scheduled Task

    Now we will schedule the backup script to be run daily. We will do this by adding a call to the script to the root crontab.

    Run the following command to open the root crontab file:

    sudo crontab -e

    Now add to the last line of the file the following:

    @daily sh /scripts/ >> /var/log/www-backup.log 2>&1

    Save the file and then wait for the script to run. You can check for errors in /var/log/www-backup.log. Once you are happy it is working, you can remove the >> /var/log/www-backup.log 2>&1 from the crontab file.