Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 三大檔案時間屬性詳解與操作實戰

編輯:Linux 教學

前言

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

操作 1:讀取檔案 → atime 更新

cat /etc/man.config
ls -l --time=atime --full-time /etc/man.config
# atime 變為現在時間

操作 2:修改權限 → ctime 更新

chmod o-r /etc/man.config
ls -l --time=ctime --full-time /etc/man.config
# ctime 變為現在時間,mtime 不變

操作 3:編輯內容 → mtime 更新(ctime 也會跟著變)

vim /etc/man.config  # 修改並存檔
stat /etc/man.config
# Modify: 新時間
# Change: 新時間(因 inode 內容變更,屬性也算變動)

一次查看三個時間:stat 指令

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 進階用法:精準控制時間

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:建立空檔(若不存在)。

重要提醒

  • cp -a 可保留 mtime/atime,但 ctime 無法保留(因 inode 重建)。
  • 檔案系統掛載選項 noatime、relatime 可減少 atime 寫入開銷,提升效能。
  • 若發現檔案時間為未來時間(常見於時區/硬體時鐘錯誤),用 touch 校正即可。

總結

掌握三時間語意與 stat/touch 操作,能精準診斷檔案活動、排查備份腳本誤判、解決編譯系統因時間錯誤導致的重建問題。

Copyright © Windows教程網 All Rights Reserved