In this guide, you will learn how to create a shell script that will backup all of your websites hosted on Ubuntu 16.04. You will also learn how to setup a scheduled task to run the backup script daily.
You may want to make regular backups of your websites just incase you get a virus or someone makes an irreversible change. In this guide, you will learn how to make a simple script that can be scheduled to archive multiple days worth of website backups. The guide assumes you have a directory structure like the following:
If you haven’t stored all your websites in
/var/www you can still use this script as the location can be changed but you will need to have each site in the same root folder.
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
www-backup.sh inside the scripts folder:
sudo vim /scripts/www-backup.sh
Now add the following code to the file and save it:
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 www-backup.sh
You can now test the backup script by running:
After running the script you should see the sites have all been backed up to
/backups/www. See below:
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
www-backup.sh script to the
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/www-backup.sh >> /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.
That’s it. You should now have a daily backup of all your websites. You can change the
DAYS_TO_KEEP option if you want more/less backups. If you have any questions or you have a better way of backing up websites on Ubuntu, leave a comment below.
If you want to know how to backup multiple databases, read: How to Schedule a Backup of All MySQL Databases on Ubuntu 16.04.