Add Scripts/mc-backup.sh

This commit is contained in:
dataprolet 2024-10-10 22:15:21 +02:00
parent 7ecf2f65bd
commit e77cb9afce
1 changed files with 87 additions and 0 deletions

87
Scripts/mc-backup.sh Normal file
View File

@ -0,0 +1,87 @@
#!/bin/usr/env bash
set -eou pipefail
#set -x
# The script creates backups of all save files in ~/.minecraft.
# Backups older than 1 day will be deleted except for the most recent one.
# Log files in ~/.minecraft that are older than 1 hour and larger than 1 GB will be deleted.
# Script assumes you have one save which is called "New World" (See line 41).
##################################################
## Write Log File
# Set directory for the log file
mkdir -p "/home/$user/.minecraft/logs"
log="/home/$user/.minecraft/logs/$(date +%Y-%m-%d_%H:%M).log"
# Redirect standard streams to the log file
exec >> >(tee -i "${log}")
exec 2>&1
##################################################
## Create Backup
# Change to directory
cd "/home/$user/.minecraft"
# Check if Minecraft is running (not the launcher)
if pgrep -f "minecraft.*java" > /dev/null; then
# Determine variable for current date
today=$(date +%Y-%m-%d_%H:%M)
# Create directory with date
mkdir -p "./backup/${today}"
# Copy save file to new directory
cp -r "./saves/New World/" "./backup/${today}"
echo "Backup ${today} created."
fi
##################################################
## Delete Old Backups
cd "/home/$user/.minecraft/backup"
# Loop through all directories
for dir in *; do
# Check if variable is a directory
if [[ -d ${dir} ]]; then
# Extract the date from the directory name
dir_day=$(echo ${dir} | cut -d '_' -f1)
# Determine the most recent directory
dir_recent=$(ls -d ${dir_day}* | sort | tail -n 1)
# Delete all directories except for the most recent one
if [[ ${dir} != ${dir_recent} ]]; then
# Check if directory is older than 1 day
find ${dir} -maxdepth 0 -type d -mtime +1 -exec echo "Backup {} deleted." \; -exec rm -rf {} +
fi
fi
done
##################################################
## Delete Old Logs
# Check if Minecraft and the launcher are not running
if ! pgrep -f "minecraft" > /dev/null; then
# Delete official logs that are larger than 1 GB and older than 1 hour
find "/home/$user/.minecraft/" -name 'launcher_log*' -size +1G -mmin +60 -exec rm {} +
# Delete logs from this script that are empty or older than 30 days
find "/home/$user/.minecraft/logs" -type f -mtime +30 -exec rm {} +
find "/home/$user/.minecraft/logs" -type f -empty -delete
fi