徹底搞明白find命令mtime含義和用法

【引言】​

大家知道,在寫shell腳本時,經常會crontab定時刪除一些文件,會經常用到 find 命令的-mtime參數,之前只是在用,沒具體理解,今天集中時間學習下。

 

Linux裏面一切皆文件,想了解文件狀態時間,就得熟悉 find命令中的-atime, -ctime,-mtime這三個參數,其中-mtime用的更多。

 

使用命令stat先看下文件或者目錄的信息:

[root@localhost products]# stat oracle19c/

  File: ‘oracle19c/’

  Size: 4096            Blocks: 8          IO Block: 4096   directory

Device: fd02h/64770d    Inode: 37224449    Links: 68

Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)

Context: unconfined_u:object_r:unlabeled_t:s0

Access: 2020-06-30 13:46:49.819926683 +0800

Modify: 2020-06-30 11:12:17.099937512 +0800

Change: 2020-06-30 11:12:17.099937512 +0800

 Birth: -

 

可以看到,關於時間信息有三個:最近訪問時間 access time (-atime)、最近更改時間modify time-mtime)和 最近狀態改動時間 change time-ctime);但也看到了Birth創建時間一項爲空,說明Linux系統下是無法查看文件的創建時間的。

 

先看下man find中的解釋,大家直接看英文,這裏不過多解釋

-atime n

File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to  have been accessed at least two days ago.

 

-ctime n

File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

 

-mtime n

File’s data was last modified n*24 hours ago.See the  comments  for  -atime  to  understand  how rounding affects the interpretation of file modification times.

 

解釋-atime, -ctime 和 -mtime參數含義:

atime: 代表最近一次訪問文件的時間,顯示一個文件的內容或者運行一個shell腳本會更新文件的atime。可用ls -lu命令查看。在kernel 2.6.30之前,文件系統默認會及時的更新atime;此後版本,只有發生以下三種情況之一纔會更新atime

1. 將分區mount的掛載的時候指定採用非relatime方式

2. atime小於ctime或者小於mtime的時候

3. 本次的access time和上次的atime超過24個小時

 

mtime: 代表最近一次文件內容被修改的時間。可用ls -l 命令查看。

 

ctime: 代表最近一次文件狀態的改變時間,是status change time,在寫入文件、更改所有者、權限或鏈接設置時隨 Inode 的內容更改而更改,文件狀態最後一次被改變的時間。可用ls -lc 命令查看。

 

在unix或linux環境中經常會用到find -mtime來找某時間點之前的文件,並在此基礎上進行處理(如定期刪除過期文件);

如何更好的理解find -mtime +N/-N/N,這裏小結下:

-mtime n : n爲數字,意思爲在n天之前的“一天之內”被更改過內容的文件

-mtime +n : 列出在n天之前(不含n天本身)被更改過內容的文件名

-mtime -n : 列出在n天之內(含n天本身)被更改過內容的文件名

 

舉個栗子:find $HOME -mtime 0

Search  for  files  in  your home directory which have been modified in the last twenty-four hours.  This command works this way because the time since each file was last modified is divided by 24 hours and  any remainder  is  discarded.   That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

 

將根目錄下24小時內更改過內容的文件列出:

find / -mtime 0

 

場景舉例:

找“5天之內被更改過的檔案名”find / -mtime -5 ;

找“5天前的那一天被更改過的檔案名”find / -mtime 5 ;

找“5天之前被更改過的檔案名”find / -mtime +5。

 

下圖來表現更直觀,以便理解記憶。

 

由以上時間軸可以看出,最右邊爲當前時,+5 代表大於等於 天前的檔案名, -5 代表小於等於 天內的檔案名,則是代表 5-6 那一天的檔案名。

 

【參考】

http://hi.baidu.com/ljm0211/item/d46591307a4985b9623aff33

【參考】

https://www.cnblogs.com/qiaopei/p/5515189.html


以下爲個人公衆號“一森咖記”,歡迎關注。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章