Quick website backup script
Backup scripts are some of the most important scripts that you will ever write. Not only do they have to work but they have to be checked and verified continually. Not having your files backed up could cause major problems that you will regret not having prevented.
I created a simple backup script which copies my web development files. These are located on my local server that I develop all my websites on and store client files, extra scripts and much more. This server is very important to what I do and access to backed up files needs to be quick and easy.
Therefore I decided to create a script which backs up my website files nightly. The script stores backups for seven days and any backups after the seven days that occur on a sunday are also kept. This ensures that I have backups for the last week and after that I have a weekly backup. Over time I will edit and enhance my script but this is what I produced just to start off with.
###
### backup our files and databases
###
### these are the directories that will be backed up and are located under /var/www ###
directories=('clients' 'form_automatic' 'repository' 'websites')
### create our directories if not present ###
for directory in ${directories[*]}
do
mkdir /var/www/backups/$directory/
done
### backup all our files ###
for directory in ${directories[*]}
do
mkdir /var/www/backups/$directory/$(date +%Y%m%d)
cp -R /var/www/$directory/* /var/www/backups/$directory/$(date +%Y%m%d)/
done
### backup all the databases ###
mkdir /var/www/backups/databases/$(date +%Y%m%d)
mysqldump -h localhost -u root --all-databases > /var/www/backups/databases/$(date +%Y%m%d)/localhost
### delete backups that are over 7 days old and did not occur on a sunday ###
arrayCount=${#directories[@]}
directories[$arrayCount + 1]=databases
for directory in ${directories[*]}
do
echo $directory
files=$(ls /var/www/backups/$directory/ | sort)
currentDate=$(date +%s)
for file in $files
do
backupDate=$(date --date $file '+%s')
daysOld=$((($currentDate - $backupDate) / 86400))
dayCreated=$(date --date $file '+%a')
if [ $daysOld -gt 7 -a $dayCreated != 'Sun' ]
then
rm -rf /var/www/backups/$directory/$file/
fi
done
done