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 touch 指令完整教學:修改檔案時間戳記、建立空檔、參考檔同步、指定日期時間多種用法實戰

編輯:關於 Linux

touch 不僅能建立空檔,更是精準控制檔案 存取時間 (atime)、修改時間 (mtime)、狀態變更時間 (ctime) 的核心工具。本文系統化說明所有參數、時間格式、實戰範例與腳本應用場景。

touch 指令參數表

語法與核心參數

touch [OPTION]... FILE...
參數長選項功能
-a --time=atime 僅修改 **存取時間** (atime)
-m --time=mtime 僅修改 **修改時間** (mtime)
-c --no-create 檔案不存在時**不建立**新檔
-r --reference=FILE 參考指定檔案的時間戳 (以該檔 atime/mtime 為準)
-d --date=STRING 解析字串時間 (支援 "2 days ago", "2024-01-15 10:30", "next Friday" 等)
-t 指定時間格式 [[CC]YY]MMDDhhmm[.ss] (無分隔符)
--time={atime|access|use|mtime|modify} 明確指定修改哪種時間
-h, --no-dereference 影響符號連結本身而非目標檔

實戰範例集

1. 建立空檔 (最常見用法)

touch log2012.log log2013.log
# 不存在則建立,存在則更新時間

2. 不建立新檔,僅更新既有檔

touch -c log2014.log
# log2014.log 不存在時不建立,不報錯

3. 同步參考檔時間

touch -r reference.log target.log
# target.log 的 atime/mtime 變為 reference.log 相同

4. 指定絕對時間 (-t 格式)

touch -t 202401151030.45 target.log
# 2024-01-15 10:30:45

5. 指定相對/自然語言時間 (-d 格式)

touch -d "2 days ago" target.log
touch -d "2024-12-25 00:00" target.log
touch -d "next Monday" target.log

6. 僅修改 atime 或 mtime

touch -a -d "1 hour ago" target.log   # 僅 atime
touch -m -d "yesterday" target.log    # 僅 mtime

腳本應用場景

建立帶時間戳的備份檔名

backup_file="config_$(date +%Y%m%d_%H%M%S).bak"
touch -t $(date -d "1 hour ago" +%Y%m%d%H%M.%S) "$backup_file"
# 檔案時間設為 1 小時前,配合 find -mmin +60 清理

同步整個目錄樹時間戳 (備份/遷移後)

# 將 /src 所有檔案時間同步到 /dst 對應檔案
cd /src
find . -type f -exec touch -r {} /dst/{} \;

測試檔案系統時間解析度

touch test.ts
stat test.ts
# 觀察 Access/Modify/Change 精度 (ext4 通常 ns 級,FAT32 2 秒)

常見誤區與注意

  • ctime (inode 狀態變更時間) **無法用 touch 修改**,僅在 chmod/chown/重命名/內容變更時由核心自動更新
  • -t 格式**不支援分隔符**,易寫錯 (如 2024-01-15 錯誤,正確 202401150000)
  • 符號連結預設修改目標檔,需加 -h 修改連結本身
  • NFS/網路檔案系統時間同步依賴伺服器 NTP,客戶端 touch 可能被覆蓋

熟練掌握 touch 的時間控制能力,能在備份腳本、測試資料準備、時間敏感應用除錯等場景大幅提升自動化程度。

Copyright © Windows教程網 All Rights Reserved