在bash腳本,如果我想刪除比在目錄15天舊文件,我可以運行:bash腳本文件移除舊的超過15個月
find "$DIR" -type f -mtime +15 -exec rm {} \;
有人可以幫我一個bash腳本刪除目錄中超過15個月的文件?
這與Bash中的ctime相同嗎?
在bash腳本,如果我想刪除比在目錄15天舊文件,我可以運行:bash腳本文件移除舊的超過15個月
find "$DIR" -type f -mtime +15 -exec rm {} \;
有人可以幫我一個bash腳本刪除目錄中超過15個月的文件?
這與Bash中的ctime相同嗎?
按照手冊頁:
-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 {} \;
是+ 60w相同我正在使用ctime? – user3409351
請注意,15個月可能更像是65周......在此基礎上,1年是52周,因此一年中的四分之一是13周,52 + 13 = 65 –
@ user3409351:是的,格式是相同的。正如可以在手冊頁中看到的那樣... – DarkDust
使用450(= 15 * 30)作爲-mtime
參數。
find $DIR -type f -mtime +450 -exec rm {} \;
如果我使用ctime,那麼+ 450是否相同? – user3409351
是的,它是一樣的。 –
一個有趣的可能性:你可以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"
這當然,假定您touch
和find
具有這些功能。
如果有可能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"
http://linux.die.net/man/8/tmpwatch正是爲這個應用而設計的。通常與cron一起使用。
請參閱http://stackoverflow.com/questions/20034415/bash-delete-all-files-older-than-1-month-but-leave-files-from-mondays?rq=1 –
但是,1月。我沒有看到類似於我想要的 – user3409351
-mtime + 65w的解決方案,可能爲65周,基於1年是52周,因此一年的四分之一是13周,52 + 13 = 65 –