簡體   English   中英

Bash-按日期/文件名刪除文件

[英]Bash - delete files by date/filename

我有一個bash腳本,它每小時在某個目錄中創建一個mysqldump備份。

備份文件的文件名包括日期和小時(按照以下架構):

backupfile_<day>-<month>-<year>_<hour>.sql.gz

並在此處澄清一些示例文件名:

backupfile_30-05-2012_0800.sql.gz
backupfile_01-06-2012_0100.sql.gz
backupfile_05-06-2012_1500.sql.gz

有人會幫助我創建一個腳本,該腳本將遍歷目錄中的所有文件,然后刪除文件,從而導致以下問題:

  1. 將備用小時備份保留一天以上的時間
  2. 每天兩次備份要保存超過一周的時間
  3. 每天一次備​​份應保留一個月以上。

我有以下腳本開頭:

#!/bin/bash
cd /backup_dir

for file in *
do
    # do the magic to find out if this files time is up (i.e. needs to be deleted)
    # delete the file
done

我已經看到許多類似這樣的腳本來執行計划的備份,並且想知道為什么今天大多數* nix發行版中的人們為什么不使用logroate實用工具來支持您感興趣的以下選項:

compress
     Old versions of log files are compressed with gzip by default.

dateext
     Archive old versions of log files adding a daily extension like YYYYMMDD instead
     of simply adding a number.

olddir directory
     Logs are moved into directory for rotation. The directory must be on the same
     physical device as the log file being rotated, and is assumed to be relative to
     the directory holding the log file unless an absolute path name is specified.
     When  this  option is used all old versions of the log end up in directory. This
     option may be overriden by the noolddir option.

notifempty
      Do not rotate the log if it is empty (this overrides the ifempty option).

postrotate/endscript
      The lines between postrotate and endscript (both of which must appear on lines by
      themselves)  are  executed  after the  log file is rotated. These directives may
      only appear inside of a log file definition.  See prerotate as well.

您可以通過遍歷文件名來解析時間戳,或者可以在find命令中使用-cmin標志(有關詳細信息,請參見man 1 find )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM