Last active
January 15, 2018 17:07
-
-
Save helsont/053b00a1fcb5b9b1981d288981eb589e to your computer and use it in GitHub Desktop.
Moves backups from a primary disk to a secondary disk when primary becomes full. Removes the oldest file from the secondary drive when secondary becomes full.
This file contains hidden or 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
PRIMARY_DIR=/mnt/primary | |
SECONDARY_DIR=/mnt/secondary | |
is_almost_full() { | |
DIR_NAME=$1 | |
cd $DIR_NAME | |
# Get percent usage of current directory in bytes | |
PERCENT=$(df -B1 `pwd` | awk 'END{print $5}') | |
# Find the most recent file | |
NEWEST=$(find -type f -printf '%p\n' | sort | tail -n 1) | |
# Calculate how big the most recent file is | |
NEWEST_BYTES=$(stat -c%s "$NEWEST") | |
# How many more bytes do we have remaining in this partition | |
REMAINING_DISK_SIZE=$(df -B1 . | awk '{ print $4 }' | tail -n 1) | |
# If we assume the next file is the exact same size, how much space | |
# would remain in the partition? | |
# Add an extra buffer just to make sure. | |
BUFFER=0 | |
SIZE_WITH_ANOTHER_FILE=$(($REMAINING_DISK_SIZE - $NEWEST_BYTES - $BUFFER)) | |
if [ $SIZE_WITH_ANOTHER_FILE -lt 0 ]; | |
then | |
echo "1" | |
else | |
echo "0" | |
fi | |
} | |
get_oldest_file() { | |
cd $1 | |
OLDEST=$(find -type f -printf '%p\n' | sort | head -n 1) | |
echo $OLDEST | |
} | |
PRIMARY_FULL=$(is_almost_full $PRIMARY_DIR) | |
SECONDARY_FULL=$(is_almost_full $SECONDARY_DIR) | |
# Primary drive is full | |
if [ $PRIMARY_FULL == "1" ] | |
then | |
# Secondary drive is also full | |
while [ $SECONDARY_FULL == "1" ] | |
do | |
# Remove the oldest file in the secondary drive | |
cd $SECONDARY_DIR | |
OLDEST="$(get_oldest_file $SECONDARY_DIR)" | |
echo "Removing oldest file: $OLDEST" | |
rm $OLDEST | |
SECONDARY_FULL=$(is_almost_full $SECONDARY_DIR) | |
done | |
# Secondary now has enough space. Move file to secondary | |
cd $PRIMARY_DIR | |
OLDEST="$(get_oldest_file $PRIMARY_DIR)" | |
echo "Moving oldest file to other backup dir $OLDEST -> $SECONDARY_DIR" | |
mv $OLDEST $SECONDARY_DIR | |
fi | |
echo "Completed moving backups." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment