2012-06-06 73 views
0

我有一個bash腳本,它在特定目錄中每小時創建一個mysqldump備份。Bash - 按日期/文件名刪除文件

備份文件的文件名包括日期和時間按以下模式:

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 
+0

你應該使用find實用程序,man find。 – morphles

+0

可能的重複:http://stackoverflow.com/questions/6099795/bash-script-to-find-old-files-based-off-date-in-file-name和http://stackoverflow.com/questions/ 3676810/bash的 - 刪除 - 基於上文件日期戳。 –

回答

0

您可以通過遍歷文件名解析您的時間戳,或者您也可以在find命令使用-cmin標誌(見man 1 find瞭解詳細信息) 。

1

我見過很多花哨的腳本,像這樣採取定時備份,不知爲什麼人們不以下列你感興趣的可供選擇的大部分* 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. 
+0

@CodeGnome:這是另一個關於logrotate的錯誤觀念,它需要root(或sudo)的訪問權限。事實上它並不需要這個。我使用它在非常嚴格的共享主機環境中進行備份文件輪換。 – anubhava

+0

你是對的:通過指定'--state '和一個合適的配置文件,logrotate * can *可以作爲不驅動的用戶運行。 –