Last active
December 26, 2020 19:04
-
-
Save kaspim/66070b34ae058c4de2246b5f3ce7cb2d to your computer and use it in GitHub Desktop.
Script for backing up folders using rsync with recycle bin folder and delayed deletion of deleted files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Rsync archive with delaying deletion | |
# Sample command: rsync_awdd.sh -s /home/kaspim -d /mnt/backup/home/kaspim -t /mnt/backup/trash/kaspim -a 90 | |
while [ ! $# -eq 0 ] | |
do | |
case $1 in | |
--help | -h) | |
echo "rsync_awdd.sh" | |
echo " -s, --source Backup source folder" | |
echo " -d, --destination Backup destination folder" | |
echo " -t, --trash Trash folder for deleted files" | |
echo " -a, --archive Number of days to keep deleted files" | |
echo " -l, --log Log file" | |
exit | |
;; | |
--source | -s) | |
shift | |
source=$(realpath -s $1) | |
shift | |
;; | |
--destination | -d) | |
shift | |
destination=$(realpath -s $1) | |
shift | |
;; | |
--trash | -t) | |
shift | |
trash=$(realpath -s $1) | |
shift | |
;; | |
--archive | -a) | |
shift | |
archive=$1 | |
shift | |
;; | |
--log | -l) | |
shift | |
log=$1 | |
shift | |
;; | |
esac | |
done | |
if [[ ! -d ${source} ]]; then | |
echo "Source folder does not exist." | tee -a ${log:-"backup.log"} | |
exit | |
fi | |
if [[ ! -d ${destination} ]]; then | |
echo "Destination folder does not exist." | tee -a ${log:-"backup.log"} | |
exit | |
fi | |
if [[ ! -d ${trash} ]]; then | |
echo "Trash folder does not exist." | tee -a ${log:-"backup.log"} | |
exit | |
fi | |
if [[ ${trash} == *${source}* || ${trash} == *${destination}* ]]; then | |
echo "Trash folder cannot be part of the source or destination folders." | tee -a ${log:-"backup.log"} | |
exit | |
fi | |
rsync -avr "${source}/" "${destination}/" | tee -a ${log:-"backup.log"} | |
while read i; do | |
if [[ ! -z ${i} ]]; then | |
path=$(dirname "${trash}/${i}") | |
mkdir -p "${path}" | |
if [[ ! -d "${path}" ]]; then | |
echo "Failed to create directory structure \"${path}\" in trash folder. The script was stopped to prevent data loss." | tee -a ${log:-"backup.log"} | |
exit | |
fi | |
mv -f "${destination}/${i}" "${trash}/${i}" | tee -a ${log:-"backup.log"} | |
touch "${trash}/${i}" | tee -a ${log:-"backup.log"} | |
fi | |
done <<< $(rsync -avr --delete --dry-run "${source}/" "${destination}/" | grep deleting | cut -d " " -f2-) | |
find "${trash}/"* -mtime +${archive:-30} -type f -delete | |
find "${trash}/"* -type d -empty -delete |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment