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/

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
mysqldump $DB > $DATADIR/$PREFIX/$DB.sql
if [[ $? -gt 0 ]];then
echo "[++--------][`date +%F--%H-%M`] Aborted. Generate database backup failed."
exit 1
echo "[++++++----][`date +%F--%H-%M`] Copy the source code project [$PROJNAME]..."
#SRC tar
if [[ $? -gt 0 ]];then
echo "[++++++----][`date +%F--%H-%M`] Aborted. Copying the source code failed."
exit 1
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/

Now you can test the backup.

cd /opt

All my databases and website files are backuped.


I want to create a backup at 02:00 every day, so I will add the next cron task:

crontab -e

0 2 * * * /opt/ | tee /var/log/backup.log

That’s all daily backup is set up.


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/


find /backup -type f -mtime +14 -exec rm -f {} \;
find /backup -type d -empty -delete

Now you should add a rotation script to cron.