定時清理文件shell腳本


一個測試機上部署多個應用,總是經常出現磁盤空間已滿,不能部署應用的情況,所以寫了個小腳本,用於定時清理日志,避免出現這種情況。


1、如果是清理固定路徑下的文件,可以直接用命令方式。       
命令方式
    (1)編寫命令:
       find /*/logs -name 'catalina.out*.log' -and  -mtime +7
     測試方法:把路徑中的*變為具體的路徑,在linux命令窗口中執行,調試結果(-mtime +7為刪除最后修改時間在7天以前的文件,可自己配置)
    (2)在linux上配置定時任務
      
        說明:因為我們使用的是系統的crontab文件,系統的crontab文件路徑為:/etc/crontab
        編輯crontab文件:
         命令:vi /etc/crontab
             輸入I;進入編輯模式
             在文件末尾寫入步驟一的命令
             配置任務定時時間:
         crontab定時配置說明: 
          *(分)  *(時)   *(天)  *(月)  *(星期)
         
          crontab中最終寫入的命令為: 23 59 * * * root find /*/logs -name 'catalina.out*.log' -and  -mtime +7 -type f |xargs rm(每天23:59分開始執行此命令
     
       (3)檢驗定時任務是否執行:
          命令: tail /var/spool/mail/root

            (4)若定時任務沒有執行,輸入命令   service crond status,確保crond狀態為 is  running

2、但是有時候需要同時清理多個路徑下的指定文件,這時,我們最好就寫個shell腳本了,下面是shell腳本的實現方式
shell腳本方式:
    (1)vi /*/deletelog.sh(腳本路徑可變,保證在path變量中就可以)
     腳本:
    #!/bin/bash         
  	workdir=("/export/Domains" "/home/admin")#可填寫多個路徑
  for wdir in ${workdir[@]}
 	 do
          echo  filepath is $wdir
          if [ $wdir =  ${workdir[0]} ] ;then
             fileStr=`find  $wdir/*/logs -type d`
             echo files is $fileStr
          else
             fileStr=`find  $wdir -type d`
             echo filee is $fileStr
          fi
         for dir in $fileStr
          do
                echo file name is $dir        
                find $dir -name '*log*' -and -mtime +7  -type f | xargs rm
                if [ $? -eq 0 ];then
                        echo $date delete $dir success!            
                else
                        echo $date delete $dir FAILD!           
                fi
          done
  done
      
    (2)賦給deletelog.sh 文件執行權限

                               命令:chmod 700    /*/logs/deletelog.sh

      (3)編輯crontab文件: 
         命令:vi /etc/crontab
             輸入I;進入編輯模式
             在文件末尾寫入步驟一的命令
             配置任務定時時間:
         crontab定時配置說明: 
          *(分)  *(時)   *(天)  *(月)  *(星期)
         
          crontab中最終寫入的命令為: * 9 * * * root /*/deletelog.sh >> /export/*/deletelog.log(帶輸出日志)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM