2016年3月1日 星期二

[Linux 常見問題] Shell - Linux shell script to count files and delete when they exceed a number

Source From HereQuestionI want to run a cron job that delete all files in a directory when it exceeds a number. For example when it become 1000 files, then delete all files in that directory. The goal is clearing cache directory.

How-ToLet's do this step by step. If your cache folder path is ./Cache, you can count the number of file under it this way:

If you don't give any argument to it, the default threshold to clean cache is 5. One usage example as below:

#./delCache.sh 6// File number under folder Cache is less than 6. So the deletation won't happen[Info] Threshold to clean Cache...6#./delCache.sh// The default threshold is 5. So the deletation will occur.[Info] Threshold to clean Cache...5[Info] Delete Cache files...#find Cache/ -type f | wc -l// Confirm the folder Cache is empty now0