2014-04-21 33 views
0

在bash腳本,如果我想刪除比在目錄15天舊文件,我可以運行:bash腳本文件移除舊的超過15個月

find "$DIR" -type f -mtime +15 -exec rm {} \; 

有人可以幫我一個bash腳本刪除目錄中超過15個月的文件?

這與Bash中的ctime相同嗎?

+0

請參閱http://stackoverflow.com/questions/20034415/bash-delete-all-files-older-than-1-month-but-leave-files-from-mondays?rq=1 –

+0

但是,1月。我沒有看到類似於我想要的 – user3409351

+0

-mtime + 65w的解決方案,可能爲65周,基於1年是52周,因此一年的四分之一是13周,52 + 13 = 65 –

回答

4

按照手冊頁:

-mtime n[smhdw] 
     If no units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started, rounded up to the next 
     full 24-hour period, is n 24-hour periods. 

     If units are specified, this primary evaluates to true if the difference between the file last modification time and the time find was started is exactly n units. Please 
     refer to the -atime primary description for information on supported time units. 

然後,在-atime

-atime n[smhdw] 
     If no units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started, rounded up to the next full 
     24-hour period, is n 24-hour periods. 

     If units are specified, this primary evaluates to true if the difference between the file last access time and the time find was started is exactly n units. Possible 
     time units are as follows: 

     s  second 
     m  minute (60 seconds) 
     h  hour (60 minutes) 
     d  day (24 hours) 
     w  week (7 days) 

     Any number of units may be combined in one -atime argument, for example, ``-atime -1h30m''. Units are probably only useful when used in conjunction with the + or - modi- 
     fier. 

因此,我們有幾個星期。 15個月* 4周/月= 60周。

find $DIR -type f -mtime +60w -exec rm {} \; 
+0

是+ 60w相同我正在使用ctime? – user3409351

+2

請注意,15個月可能更像是65周......在此基礎上,1年是52周,因此一年中的四分之一是13周,52 + 13 = 65 –

+0

@ user3409351:是的,格式是相同的。正如可以在手冊頁中看到的那樣... – DarkDust

0

使用450(= 15 * 30)作爲-mtime參數。

find $DIR -type f -mtime +450 -exec rm {} \; 
+0

如果我使用ctime,那麼+ 450是否相同? – user3409351

+0

是的,它是一樣的。 –

0

一個有趣的可能性:你可以touch時間戳15 months ago一個tmp文件,並與(否定)-newer標誌find使用它:

a=$(mktemp) 
touch -d '15 months ago' -- "$a" 
find "$DIR" -type f \! -newer "$a" -exec rm {} + 
rm -- "$a" 

這當然,假定您touchfind具有這些功能。

如果有可能mktemp在您的目錄$DIR的子目錄中創建文件,它將變得非常混亂,因爲在過程結束之前可以刪除引用「$ a」的文件。在這種情況下,100%肯定的是,使用(否定)-samefile測試:

find "$DIR" -type f \! -newer "$a" \! -samefile "$a" -exec rm {} + 

當然你也可以使用find-delete命令,如果您find支持它。這將給:

a=$(mktemp) 
touch -d '15 months ago' -- "$a" 
find "$DIR" -type f \! -newer "$a" \! -samefile "$a" -delete 
rm -- "$a" 
相關問題