Self cleaning download directory under Ubuntu
Like many of you I like to download “stuff”. But every now and then I run out of space on my hard-drive and it’s clean up my download directory time. The problem is I don’t know that’s in there any more and when i do look it’s cool stuff I never look at but still want to keep. Secretly I’m an Internet pack rat that wants his own copy of anything cool.
The secret to not having space on your hard-drive is to have “stuff” you never look at go missing without your knowledge. And that’s what this handy script is all about.
Note: this script doesn’t use tmpreaper! and has a variable grace time.
Preparation.
Before you start using this there are a couple of things you need.
- A directory especially for all your downloads. That means neither /tmp or your home directory.
- Install the ‘bc‘ package. It is a command line calculator which is fairly easy to use in bash scripts. I’m using bc to calculate a variable grace time depending on how much room I have left on disk.
How it works.
First you have to make your download directory and have look in /etc/fstab to find out on which partition your download directory is.
Now then, first we are going to get disk space statistics using the df command and filter out everything but the line for the partition our download directory is on using grep. This is stored in a shell variable named DF. The next line strips out excess spaces from the DF variable.
After that we can easily split out the values for used space, free space and total space on the disk. The cut command can use a ‘ ‘ or space as a field delimiter.
Now the arithmetic. I’ve chosen to use this function to calculate grace time.
(free-space/used-space)* 1 Year
When the partition is half-full it’ll leave my “stuff” alone for a year. The fraction will shorten the grace time faster and faster the more space is used making the cleanup more and more aggressive. Bc will outputĀ a number with quite some decimal places which we don’t need so we’ll loop it though ‘cut’ again and get the first field using ‘.’ as a delimiter.
Finally find the “old stuff” and remove it. Then remove empty directories. And we are done!
This script has been a daily cronjob on my downloads directory for about a year now and I’m very happy with it. I hope this is some use to you.
The script
#!/bin/bash
DOWNLOAD_DIR=YOURDIRECTORY
PARTITION=YOUPARTITION
#get the PARTITION statistics and strip exces white space.
DF=$(df -l |grep $PARTITION)
DF=$(echo ${DF/ / })
#And split it up in total space, used space and free space.
#TOTAL=$(echo $DF | cut -d’ ‘ -f 2)
USED=$(echo $DF |cut -d’ ‘ -f 3)
FREE=$(echo $DF | cut -d ‘ ‘ -f 4)
GRACE_TIME=$(echo “($FREE/$USED)*365″ | bc -l |cut -d “.” -f 1)
#echo $GRACE_TIME
IFS=’
‘
#removing files.
for FILE in $(find $DOWNLOAD_DIR -type f -atime +${GRACE_TIME} -print)
do
rm $FILE
# echo $FILE
done
#remove Empty directories.
for DIR in $(find $DOWNLOAD_DIR -type d -empty -print)
do
rmdir $DIR
# echo $DIR
done