Linux 檔案擁有三個時間戳記,初學者極易混淆。本文透過實際指令演示,清楚區分 mtime(修改時間)、ctime(狀態改變時間)、atime(存取時間),並說明 stat、touch 等工具的進階用法。
| 時間屬性 | 英文 | 觸發條件 | 指令查看範例 |
|---|---|---|---|
| 修改時間 | mtime | 檔案內容被修改(編輯、寫入、截斷) | ls -l(預設)、ls -l --time=mtime |
| 狀態改變時間 | ctime | 檔案屬性變更(權限、擁有者、連結數、移動、重命名) | ls -l --time=ctime |
| 存取時間 | atime | 檔案內容被讀取(cat、less、grep、cp 來源端) | ls -l --time=atime |
# 初始狀態
ls -l --full-time /etc/man.config
# -rw-r--r-- 1 root root 4522 2007-11-17 18:47:54 ... mtime
ls -l --time=atime --full-time /etc/man.config
# -rw-r--r-- 1 root root 4522 2010-03-15 14:20:20 ... atime
ls -l --time=ctime --full-time /etc/man.config
# -rw-r--r-- 1 root root 4522 2008-07-11 16:21:55 ... ctime
cat /etc/man.config
ls -l --time=atime --full-time /etc/man.config
# atime 變為現在時間
chmod o-r /etc/man.config
ls -l --time=ctime --full-time /etc/man.config
# ctime 變為現在時間,mtime 不變
vim /etc/man.config # 修改並存檔
stat /etc/man.config
# Modify: 新時間
# Change: 新時間(因 inode 內容變更,屬性也算變動)
stat /etc/man.config
File: '/etc/man.config'
Access: 2010-03-15 14:24:30.000000000 +0800 # atime
Modify: 2007-11-17 18:47:54.000000000 +0800 # mtime
Change: 2010-03-15 14:28:34.000000000 +0800 # ctime
touch [選項] 檔案
選項:
-a 僅修改 atime
-m 僅修改 mtime
-c 不建立檔案(僅修改既有檔案時間)
-t 指定時間格式 [[CC]YY]MMDDhhmm[.ss]
-d 字串日期,支援 "2 days ago", "yesterday 10:00" 等
touch -d "2 days ago" file:將 atime、mtime 設為兩天前,ctime 不變。touch -t 202301011200 file:設定為 2023-01-01 12:00。touch newfile:建立空檔(若不存在)。noatime、relatime 可減少 atime 寫入開銷,提升效能。touch 校正即可。掌握三時間語意與 stat/touch 操作,能精準診斷檔案活動、排查備份腳本誤判、解決編譯系統因時間錯誤導致的重建問題。