Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 檔案時間屬性深度解析:mtime、ctime、atime 差異與 touch 指令精準控制

編輯:Linux 系統常見問題解答

三種時間屬性定義

時間類型英文全名觸發條件查看指令
修改時間Modification Time (mtime)檔案內容被修改ls -l (預設)
狀態改變時間Change Time (ctime)檔案屬性變更 (權限、擁有者、連結數、移動等)ls -l --time=ctime
存取時間Access Time (atime)檔案內容被讀取 (cat、vim 開啟、grep 等)ls -l --time=atime

實際測試範例

$ ls -l uconv.h
-rw-rw-r-- 1 work work 1808 Jul 23 2013 uconv.h   # mtime

$ ls -l --time=ctime uconv.h
-rw-rw-r-- 1 work work 1808 Jul 23 2013 uconv.h   # ctime

$ ls -l --time=atime uconv.h
-rw-rw-r-- 1 work work 1808 Dec 12 2013 uconv.h   # atime (較新,因被讀取)

touch 指令精準修改時間

常用參數

參數功能範例
-a僅修改 atimetouch -a file
-m僅修改 mtimetouch -m file
-c不建立新檔 (僅修改既有檔)touch -c newfile
-d STRING指定日期字串touch -d "2 days ago" file
-t STAMP指定時間戳 [[CC]YY]MMDDhhmm[.ss]touch -t 202401151430 file
-r FILE參考其他檔案時間touch -r ref.txt target.txt

實戰演示

# 將 mtime 和 atime 設為 2 天前,ctime 不變
$ touch -d "2 days ago" uconv.h
$ ll uconv.h; ll --time=atime uconv.h; ll --time=ctime uconv.h
-rw-rw-r-- 1 work work 1808 Jun 13 18:17 uconv.h   # mtime
-rw-rw-r-- 1 work work 1808 Jun 13 18:17 uconv.h   # atime
-rw-rw-r-- 1 work work 1808 Jun 15 18:17 uconv.h   # ctime (未變)

# 指定精確時間 2014-06-14 20:20
$ touch -t 201406142020 uconv.h
$ ll uconv.h; ll --time=atime uconv.h; ll --time=ctime uconv.h
-rw-rw-r-- 1 work work 1808 Jun 14 20:20 uconv.h   # mtime
-rw-rw-r-- 1 work work 1808 Jun 14 20:20 uconv.h   # atime
-rw-rw-r-- 1 work work 1808 Jun 15 18:23 uconv.h   # ctime 變為當前 (因屬性被修改)

cp -a 保留時間屬性測試

$ cp -a uconv.h uconv.h1
$ ll uconv.h1; ll --time=atime uconv.h1; ll --time=ctime uconv.h1
-rw-rw-r-- 1 work work 1808 Jun 14 20:20 uconv.h1   # mtime 保留
-rw-rw-r-- 1 work work 1808 Jun 15 18:25 uconv.h1   # atime 保留
-rw-rw-r-- 1 work work 1808 Jun 15 18:27 uconv.h1   # ctime 變新 (建立新 inode)

結論:cp -a 可保留 mtime/atime,但 ctime 必然更新 (新 inode 建立)。

應用場景與注意事項

  • 備份驗證:比對來源/目的 mtime 確認同步完整性
  • 找尋近期異動:find /path -mtime -1 (1 天內修改)、-ctime -1 (1 天內屬性變更)
  • 時間戳偽造風險:touch 可竄改時間,審計需結合 inode 變更歷程 (ctime) 或檔案系統日誌
  • noatime 掛載選項:/etc/fstab 加入 noatime 可減少磁碟寫入,提升效能 (atime 不再更新)
Copyright © Windows教程網 All Rights Reserved