Script That Deletes Old Files to Keep Disk From Filling Up

Fri 19 August 2011 Category: Linux

When a disk has no free space left, all kinds of trouble can occur.

Therefore, I've created a script that monitors the used space of a volume and deletes the oldest file if a certain threshold is reached.

The script will keep on deleting the oldest file present on disk until used capacity is below the threshold.

So you can tell the script to monitor volume /storage and delete old files if the used capacity is bigger than 95 percent.

The script works like this:

./ <mount point> <percentage>

The mount point represents a volume or physical disk. The percentage represents the maxium used capacity threshold.

The script reads the output of the 'df -h' command to determine 'disk' usage.


bash-3.2$ ./ /Volumes/usb 92


Usage of 90% is within limit of 92 percent.

How let's see what happens when the threshold is exceeded.

bash-3.2$ sudo ./ /Volumes/usb 92


Usage of 97% exceeded limit of 92 percent.
Deleting oldest file /Volumes/usb/a/file02.bin
Usage of 91% is within limit of 92 percent.

Here you notice that an old file is deleted and that the script checks again if there is now enough free space. If not, another file would have been deleted.

If you have a need for it, have fun. It was a fun little scripting exercise.

The script works under Linux and Mac OS X.