Backup-Restore Linux

Backup
# slow singlethreaded gzip
tar -czpf /backup/backup.tar.gz --exclude=/backup --one-file-system /

# with multithreaded gzip (pigz)
apt install pigz -y
tar -I pigz -cpf /backup/backup.tar.gz --exclude=/backup --one-file-system /

# upload to backup server
rsync -avP /backup/* bkpsrv:/share/
Restore
# prepare filesystem and unpack backup
fdisk /dev/sda
mkfs.ext4 /dev/sda1
mount /dev/sda1 /mnt
rsync -avP bkpsrv:/share/backup.tar.gz /mnt/
tar -xpzf /mnt/backup.tar.gz -C /mnt --numeric-owner

# restore grub
mount --bind /dev /mnt/dev
mount --bind /sys /mnt/sys
mount --bind /proc /mnt/proc
chroot /mnt

# GRUB 1 (Debian / Ubuntu / RHEL 6)
dpkg-reconfigure grub-pc
grub-install --recheck /dev/sda

# GRUB 2 (RHEL 7)
grub2-install /dev/sda
grub2-mkconfig -o /boot/grub2/grub.cfg

# manually recheck configs (dont forget about UUIDs in fstab)
less /etc/fstab
less /boot/grub/grub.cfg
Backup automation script with rotation
!/bin/bash

MAXBACKUPS=3
BACKUPSDIR=/backup
DATE=`date +"%Y%m%d.%H%M%S"`

# cleanup
yum clean all
rm -rf /var/cache/yum/*
rm -rf /var/lib/yum/repos/*
rm -rf /var/lib/yum/yumdb/*
rm -rf /var/lib/yum/history/*

# backup
tar --use-compress-program=pigz -cpf $BACKUPSDIR/backup-$DATE-boot.tar.gz --one-file-system /boot
tar --use-compress-program=pigz -cpf $BACKUPSDIR/backup-$DATE-root.tar.gz --exclude={/backup,/boot,/data,/var/log/*,/var/cache/*,/var/spool/mail/*,*.log,/root/.cache} --one-file-system /
tar --use-compress-program=pigz -cpf $BACKUPSDIR/backup-$DATE-data.tar.gz --exclude={*.log} --one-file-system /data

# clenaup
cd $BACKUPSDIR
ls -A1t | grep .gz | grep boot | tail -n +$(($MAXBACKUPS+1)) | xargs rm
ls -A1t | grep .gz | grep root | tail -n +$(($MAXBACKUPS+1)) | xargs rm
ls -A1t | grep .gz | grep data | tail -n +$(($MAXBACKUPS+1)) | xargs rm

# rebuild deleted data
rpm --rebuilddb

exit 0