Skip to content

Instantly share code, notes, and snippets.

@fredsted
Created August 28, 2017 07:04
Show Gist options
  • Save fredsted/1d1b3184d28bf3946b4906fc2a8afab1 to your computer and use it in GitHub Desktop.
Save fredsted/1d1b3184d28bf3946b4906fc2a8afab1 to your computer and use it in GitHub Desktop.
Script to delete old files when disk getting full
#/bin/sh
# This script deletes old files when the disk is getting full.
# It will always delete the oldest file or directory. Can be run
# in a cronjob every few minutes.
# Configurables
STORAGEDIR=/var/backups
FILESYSTEM=$(df -h | grep -o '/dev/[a-z0-9]*') # or whatever filesystem to monitor
CAPACITY=90 # delete if FS is over $CAPACITY % of usage
# Proceed if filesystem capacity is over than the value of CAPACITY (using df POSIX syntax)
# using [ instead of [[ for better error handling.
CURR_CAPACITY=$(df -P $FILESYSTEM | awk '{ gsub("%",""); capacity = $5 }; END { print capacity }')
if [ $CURR_CAPACITY -gt $CAPACITY ]
then
FILENAME=$(ls -1t $STORAGEDIR | tail -n1)
rm -rf "$STORAGEDIR/$FILENAME"
echo "$(date) Capacity: $CURR_CAPACITY % - Deleted: $STORAGEDIR/$FILENAME" >> ~/autodelete.log
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment