09 April 2013

Clean (script)

I really do not know if this can be achieved automatically in a different/more effective way. The reason why I wrote this simple script is that I wanted to clean certain directories in my filesystem. The idea started with /tmp but I decided to include other directories such as the Trash bin.
What the script does is: One after the other, it tests whether the directories are empty or not. If they are empty it does nothing. If they contain files the script removes them, including the dot files.
BUGS: The script has, at least, one bug. Since it is set -e it stops after the very last iteration if there are hidden files in /tmp which cannot be removed if you run the script by hand as normal user. That is why I put /tmp in the last place. When it stops, all the other files are already deleted so it does not really matter whether it stops or not.
Why do I use set -e? Because I think that the rm -rf command toghether with a * wildcard is way too dangerous to let it loose.
Why keeping a log file? Because I can :)
Why to log ${DIR} is empty? This way I can adjust cron/anacron timing. For example, if I run it weekly and after a week the ${DIR} is empty, I may prefer to run it after two weeks or so. Do you get the idea? ;)
Why does the log file not include a list of all the deleted files? Who cares about the contents of Trash or tmp anyway? Especially after they have already been deleted.
Why not write a log function instead of redirecting the output to a log file?Because I'm too lazy to do that? Now seriously, the idea was in mind but the script is too simple to do that. Perhaps one day it will get better and grow bigger, and I do finally write that function then. (Note: That is not likely going to happen).
What is the best way to use this script? To tell you the truth, the best way to use this script is simply NOT using it. I mean that it really is very dangerous to remove files like that, hence the 'Big Fat Warning' on the header of the script. But still, if you want to give it a try, first read it, understand what the script does and adapt it to your needs.
Then, I recommend you add the script to, say, /etc/cron.monthly so that it is run by your system on a monthly basis.
Here is the script:

 set -e

 # Script to clean directories. The ls -A means that it does not list . & ..
 # BIG FAT WARNING: rm -rf is potentially dangerous. Use this at your own risk!

 # Directories to clean.

 TRASH="/home/chals/.local/share/Trash/files" # Trash in Xfce

 # Where to write the log file.


 # Let's do it!

         if [ "$(ls -A ${DIR})" ]
                 rm -rf ${DIR}/* && rm -rf ${DIR}/.??* > /dev/null 2>&1 # Remove dot files too.
                 echo "$(date) Cleaning ${DIR} :) " >> ${LOG_FILE} 
                 echo "$(date) Nothing to be done, ${DIR} is empty :( " >> ${LOG_FILE}