-
-
Save apizz/41c2fe8affe64d004734aa0de22cfd57 to your computer and use it in GitHub Desktop.
#!/bin/bash | |
# | |
# Script for running automated backups for Snipe-IT Docker containers and removing old backups | |
# | |
# Mean to be used as part of a crontab | |
# | |
# Limits its search for backups to clean up to those in the 'BACKUP_DIR' folder, so | |
# you can create folders in this location to keep any manual backups for historical purposes | |
# | |
# Docker container name to backup | |
CONTAINER="${1}" | |
# Snipe-IT Docker container backup location | |
BACKUP_DIR="/var/www/html/storage/app/backups/" | |
# Number of backups to keep | |
MAX_BACKUPS="14" | |
# Verify a container name is supplied | |
if [ "$CONTAINER" = "" ]; then | |
/bin/echo "No value supplied for 'CONTAINER'. Please run the script followed by the container name. ex. sh script.sh <container_name>" | |
exit 1 | |
fi | |
# First, complete a backup | |
/bin/echo "Creating database backup for ${CONTAINER} ..." | |
docker exec "$CONTAINER" /usr/bin/php /var/www/html/artisan snipeit:backup | |
# Process existing backups for cleanup | |
BACKUPS=$(docker exec "$CONTAINER" /usr/bin/find "$BACKUP_DIR" -maxdepth 1 -type f | /usr/bin/sort -r) | |
BACKUP_NUM=$((${MAX_BACKUPS} + 1)) | |
OLD_BACKUPS=$(echo $BACKUPS | tail -n +${BACKUP_NUM}) | |
# If old backups found, remove them | |
if [ "$OLD_BACKUPS" != "" ]; then | |
echo "Cleaning up old backups ..." | |
for f in $OLD_BACKUPS; do | |
echo "Removing old backup: ${f} ..." | |
docker exec "$CONTAINER" rm $f | |
done | |
else | |
echo "No backups to clean. Done." | |
fi | |
exit |
grimurd
commented
Sep 2, 2019
@grimurd so it appears something with the OLD_BACKUPS commands / formatting is to blame here (echo $BACKUPS | tail -n +${BACKUP_NUM}
). I'm honestly not sure what's different between our CentOS setups, but I can confirm that I only have 14 backups on all my Snipe-IT instances, and this was both before and after Snipe updated their naming scheme to include "snipe-it" in the ZIP backup filename.
I'd play around with the commands used in OLD_BACKUPS
on your end to get just the backups that you'd want to remove based on your desired # of historical backups. If you get something working, post it here so I can test on my end. It's very possible there's a better way to do this than what I've come up with here.
I know this is old, but what about the SQL container? Does that need to be done?
Hi there,
thanks for providing this backup script :-)
Working on Debian Bullseye I faced exactly the same problem as @grimurd described (OLD_BACKUPS variable is always empty). While not being a Bash guy I fiddled around and found a working solution. Instead of using (echo $BACKUPS | tail -n +${BACKUP_NUM})
I changed it to (echo "$BACKUPS" | tail -n +${BACKUP_NUM})
. With this change "$BACKUPS"
, the backup script works now flawlessly in my setup.