Skip to content

Instantly share code, notes, and snippets.

@dgpro
Last active April 1, 2019 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgpro/05672005274ed665206c66298e6efba4 to your computer and use it in GitHub Desktop.
Save dgpro/05672005274ed665206c66298e6efba4 to your computer and use it in GitHub Desktop.
SSH Script to cleanup folder space by removing older files. E.g. for backups
#!/bin/bash
# directory to cleanup
DIR=$1
# how much to free up in Gb
SIZE=$2
# factor to size conversion
FACTOR=1048576
MAX_FREE_SIZE=20
if [ "$DIR" = "" ]
then
echo "ERROR: directory not specified"
exit 1
fi
if ! cd $DIR
then
echo "ERROR: unable to chdir to directory '$DIR'"
exit 2
fi
if [ "$SIZE" = "" ] || [ "$SIZE" -gt "$MAX_FREE_SIZE" ]
then
SIZE=1 # default size
fi
# convert GB to KB
SIZE=$(($SIZE * FACTOR))
actualSize() {
# space available in Kb, take second line only
echo $(df --output=avail --type=ext4 | tail -n 1)
# space used
#echo $(du -sb | cut -f1)
}
#echo "$(actualSize) - $SIZE"
if [ $(actualSize) -lt "$SIZE" ]
then
#
# Get list of files, oldest first.
# Delete the oldest files until
# free space is above the limit. Just
# delete regular files, ignore directories.
#
ls -rt | while read FILE
do
if [ -f "$FILE" ]
then
if rm -f "$FILE"
then
# echo "Deleted $FILE"
if [ $(actualSize) -ge "$SIZE" ]
then
# we're below the limit, so stop deleting
exit
fi
fi
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment