Skip to content

Instantly share code, notes, and snippets.

@ynrng
Created June 7, 2024 04:15
Show Gist options
  • Save ynrng/8619ffd2600e8316eecb99fc12a84df8 to your computer and use it in GitHub Desktop.
Save ynrng/8619ffd2600e8316eecb99fc12a84df8 to your computer and use it in GitHub Desktop.
backup current whole directory including hidden files to a target position --target_dir with same name folder created; keep --n copies and delete oldest one automatically. Usage in first few lines.
#!/bin/bash
# Open the crontab file for editing:
# sudo crontab -e
# Add the following line to the crontab file:
# 0 0 * * * /dir/to/backupdir.sh --target_dir /dir/to/backups --n 24
TARGET_DIR="/media/yan"
MAX_BACKUPS=1
# Parse command line arguments
while (( "$#" )); do
case "$1" in
--target_dir)
TARGET_DIR="$2"
shift 2
;;
--n)
MAX_BACKUPS="$2"
shift 2
;;
--) # end argument parsing
shift
break
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
ROOT_DIR="$(cd $( dirname ${BASH_SOURCE[0]} ) && pwd)"
CURRENT_DIR_NAME=$(basename $(dirname "$0"))
# echo $ROOT_DIR
# echo $CURRENT_DIR_NAME
# # Variables
SOURCE_DIR="${ROOT_DIR}/."
BACKUP_DIR="${TARGET_DIR}/${CURRENT_DIR_NAME}"
mkdir -p ${BACKUP_DIR}
echo "Backing up ${SOURCE_DIR} to ${BACKUP_DIR} with $MAX_BACKUPS backups." >> "$BACKUP_DIR/$CURRENT_DIR_NAME.log"
# Create a new backup
NEW_BACKUP="${BACKUP_DIR}/backup_$(date +%Y%m%d%H)"
rsync -azr ${SOURCE_DIR} ${NEW_BACKUP} --exclude 'devel' --exclude 'build' --exclude 'logs' --exclude '.catkin_tools'
# Delete the oldest backup if there are too many backups
BACKUP_COUNT=$(ls -1 ${BACKUP_DIR}/ | grep backup_ | wc -l)
if (( BACKUP_COUNT > MAX_BACKUPS )); then
OLDEST_BACKUP=$(ls -1 ${BACKUP_DIR}/ | grep backup_ | head -n 1)
echo "deleting backup ${OLDEST_BACKUP}." >> "$BACKUP_DIR/$CURRENT_DIR_NAME.log"
rm -rf ${OLDEST_BACKUP}gi
fi
echo "backup ${NEW_BACKUP} completed." >> "$BACKUP_DIR/$CURRENT_DIR_NAME.log"
@ynrng
Copy link
Author

ynrng commented Jun 7, 2024

change NEW_BACKUP to include min and sec if frequency higher than an hour

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment