Earlier tonight I created a little script that will run in cron on a Linux server. The script counts the number of directories and files in a specific directory and if the count is above Y then it deletes directories and files older than X number of days. In the example script below the number of items (directories and files) that have to be located in the directory before the script to delete files older than a specific date is 10. If there are ten items then the script will delete items older than 90 days. Below the script is the entry made in a specific users cron on the Linux server.
Script To Delete Items Older Than X Days If Y Items Exist In The Directory:
- #!/bin/bash
- COUNT=`/bin/ls -l /home/upload/filesbydate | /usr/bin/wc -l`
- MINDIRS=10
- if [[ $COUNT -gt $MINDIRS ]]
- then
- /usr/bin/find /home/upload/filesbydate -type d -mtime +90 -exec rm -rf \{\} \;
- else
- echo NOT ENOUGH ITEMS
- fi
A brief explanation of the script follows. There are two variables in the script which are COUNT (grabs the count of the number of items in the directory we are working in) and MINDIRS which sets the minimum number of items in the directory before the rm command will run. The COUNT directory gets the count by listing the files in the directory with ls and provides a count of that file list using wc. Next the if statement verifies there are enough files and/or directories existing before it will execute the find and rm commands. The command that actually does the file/directory removal first finds files in the specified directory that are older than 90 days (it uses mtime +X for this) and then executes the rm command. Also notice the “-type” switch which specifies directories since in my situation all files were uploaded within subdirectories underneath the filesbydate directory. If you needed to find and delete files you would use the “f” for files such as “-type f”. Notice the rm command has two switches which include “-r” for recursive and “-f” for force. The above bash script was saved as cleanup.sh and then added to the upload users crontab as shown in the below cron entry.
Entry Added To Upload Users Cron:
- # Clean Up Files In filesbydate Directory
- 44 4 * * * /usr/local/bin/cleanup.sh > /var/log/cleanup
The above cron entry will run once a day at 4:44 AM during the timezone set on the server. Before adding the cron entry make sure to touch the /var/log/cleanup file and provide it the proper permissions to be written to by the users cron that the above entry was added to. This log will provide you information on what items are deleted and how often there are not enough items in the filesbydate directory.