2016年3月1日 星期二

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

Source From Here 
Question 
I 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-To 
Let's do this step by step. If your cache folder path is ./Cache, you can count the number of file under it this way: 
# ls Cache/
總計 0
drwxr-xr-x. 2 root root 6 3月 1 16:02 folder
-rw-r--r--. 1 root root 0 3月 1 15:59 test1
-rw-r--r--. 1 root root 0 3月 1 15:59 test2
-rw-r--r--. 1 root root 0 3月 1 15:59 test3
-rw-r--r--. 1 root root 0 3月 1 15:59 test4
-rw-r--r--. 1 root root 0 3月 1 15:59 test5


// Use command find with argument:
// -type c
// File is of type c:
// b: block (buffered) special
// c: character (unbuffered) special
// d: directory
// p: named pipe (FIFO)
// f: regular file
// l: symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype.
// s: socket

# find Cache/ -type f // List all regular file 
Cache/test1
Cache/test2
Cache/test3
Cache/test4
Cache/test5

# find Cache/ -type f | wc -l // Count the number of regular file
5
Based on the above description, we can write a simple shell: 
- delCache.sh 
  1. #!/bin/sh  
  2. CACHE_DIR='./Cache'  
  3.   
  4. T=5  
  5. if [ "$#" -gt 0 ]; then  
  6.     T=$1  
  7. fi  
  8. echo -e "\t[Info] Threshold to clean Cache...$T"  
  9.   
  10. if [[ `find $CACHE_DIR -type f | wc -l` -ge $T ]]; then  
  11.     echo -e "\t[Info] Delete Cache files..."  
  12.     find $CACHE_DIR -type f -exec rm -f {} \;  
  13. fi  
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 now
0

Supplement 
[Linux 命令] find : 尋找特定字串的檔案或目錄 
Linux find 命令使用詳解

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...