Last active
April 1, 2019 09:01
-
-
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
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
#!/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