In this guide, I will show you how to create a backup of the database and site files using a simple bash script. I will also show you how you can automate the process and set up the archive rotation.
Bash Script
Just copy the next script to your server. In my case, it will be /opt/backup.sh
#!/bin/bash
PROJNAME=unihost.com
DBNAME=$(mysqlshow | sed 's/[|+-]//g' | grep -v Databases | grep -v information_schema | grep -v performance_schema | grep -v mysql | sed 's/^[ \t]*//;s/[ \t]*$//' | sort | sed '/./,$!d') #DB name
DATADIR=/backup #backup path
SRC=/var/www/unihost #folder to backup
PREFIX=`date +%F`
#start backup
echo "[--------------------------------[`date +%F--%H-%M`]--------------------------------]"
echo "[----------][`date +%F--%H-%M`] Run the backup script..."
mkdir -p $DATADIR/$PREFIX 2> /dev/null
echo "[++--------][`date +%F--%H-%M`] Generate a database backup..."
#MySQL dump
for DB in $DBNAME
do
mysqldump $DB > $DATADIR/$PREFIX/$DB.sql
done
if [[ $? -gt 0 ]];then
echo "[++--------][`date +%F--%H-%M`] Aborted. Generate database backup failed."
exit 1
fi
echo "[++++++----][`date +%F--%H-%M`] Copy the source code project [$PROJNAME]..."
#SRC tar
tar -czPf $DATADIR/$PREFIX/$PROJNAME.tar.gz $SRC
if [[ $? -gt 0 ]];then
echo "[++++++----][`date +%F--%H-%M`] Aborted. Copying the source code failed."
exit 1
fi
echo "[++++++++--][`date +%F--%H-%M`] Copy the source code project [$PROJNAME] successfull."
echo "[+++++++++-][`date +%F--%H-%M`] Stat datadir space (USED): `du -h $DATADIR | tail -n1`"
echo "[+++++++++-][`date +%F--%H-%M`] Free HDD space: `df -h /|tail -n1|awk '{print $4}'`"
echo "[++++++++++][`date +%F--%H-%M`] All operations completed successfully!"
exit 0
You need to change:
PROJNAME — it’s just a name
DATADIR — folder where backups are stored
SRC — folder what will be backuped
Give execute permission the script
chmod +x /opt/backup.sh
Now you can test the backup.
cd /opt
./backup
All my databases and website files are backuped.
Automation
I want to create a backup at 02:00 every day, so I will add the next cron task:
crontab -e
0 2 * * * /opt/backup.sh | tee /var/log/backup.log
That’s all daily backup is set up.
Rotation
In order to remove old archives and save disk space. I will set up an archive rotation. In my case, I will remove files older than 14 days.
I will create a new bash script /opt/rotate.sh
#!/bin/bash
find /backup -type f -mtime +14 -exec rm -f {} \;
find /backup -type d -empty -delete
Now you should add a rotation script to cron.