Tag Archives: backup

Backup script for Linux Server in bash

bu
If you are a hardcore linux admin you may use complex backup system like the Bacula or AMANDA or other.
But for simple case it is enough to use bash script. It creates a folder with copied files from filesystem and dumped databases from MySql server. In my case here it is backup.sh:

#!/bin/sh

##--- SETTINGS
ROOT_PATH=$1
DAYS_KEEP=$2

BU_FILES="/etc"
BU_FILES="$BU_FILES;/usr/local/apache2"
BU_FILES="$BU_FILES;/usr/serv/apache/www"

EXCLUDE_PATH_1="/usr/serv/apache/www/stuff"

MYSQL_USER=backuper
MYSQL_PASS='backuper_passwd'

##--- COMMON ENV
DATESTAMP=$(date +%Y-%m-%d)
BU_PATH=${ROOT_PATH}/${DATESTAMP}

##--- BACKUP FILES
FILE_PATH=${BU_PATH}/files
if [ ! -e ${FILE_PATH} ]; then
    mkdir -p ${FILE_PATH}
fi

cd $FILE_PATH

# create backups securely - this will give 660 for new file creation
umask 006

for dir in $(echo $BU_FILES | tr ";" "\n")
do
  printf "Backup dir '${dir}' ... "
  if [ ! -e ${dir} ]; then
    echo "ERROR: Directory not found"
  else
    tar zcfP ${FILE_PATH}/`basename ${dir}`.tar.gz ${dir} --exclude ${EXCLUDE_PATH_1}
    echo "OK"
  fi
done

##--- BACKUP DATABASES
MYSQL_PATH=${BU_PATH}/mysql
if [ ! -e ${MYSQL_PATH} ]; then
    mkdir -p ${MYSQL_PATH}
fi

cd $MYSQL_PATH

# create backups securely - this will give 660 for new file creation
umask 006

# list MySQL databases and dump each one
MYSQL_DB_LIST=`mysql -u $MYSQL_USER -p"$MYSQL_PASS" -e'show databases;'`
MYSQL_DB_LIST=${MYSQL_DB_LIST##Database}
for DB in $MYSQL_DB_LIST;
do
  printf "Backup DB '${DB}' ... "
  mysqldump --single-transaction -u $MYSQL_USER -p"$MYSQL_PASS" --opt --flush-logs --databases $DB | gzip > ${MYSQL_PATH}/${DB}.sql.gz
  echo "OK"
done

# all dbs
printf "Backup all DBs ... "
mysqldump --single-transaction -u $MYSQL_USER -p"$MYSQL_PASS" -A --opt --events --ignore-table=mysql.event --flush-logs | gzip > ${MYSQL_PATH}/all_dbs.sql.gz
echo "OK"

##--- REMOVE backups older than $DAYS_KEEP
find ${ROOT_PATH}/* -mtime +$DAYS_KEEP -exec rm -rf {} \; 2> /dev/null

cd /var

The example usage:

  ./backup.sh /var/backups 30

where:
/var/backups – path to dir where backup will be placed;
30 – days count of backups to save;

You can download all files: backup_scripts