touch — 建立空檔案或更新時間戳記
建立空白檔案,或更新現有檔案的時間戳記。
語法
touch [選項] 檔案...
常用選項
| 選項 | 說明 | 範例 |
|---|---|---|
-a |
只更新存取時間(atime) | touch -a file.txt |
-m |
只更新修改時間(mtime) | touch -m file.txt |
-t STAMP |
設定為指定時間(格式:[[CC]YY]MMDDhhmm[.ss]) | touch -t 202601011200 file.txt |
-d 字串 |
使用指定的日期字串 | touch -d "2026-01-01 12:00" file.txt |
-r 參考檔 |
使用參考檔的時間戳記 | touch -r ref.txt target.txt |
-c, --no-create |
若檔案不存在則不建立(只更新現有檔案) | touch -c maybe-exists.txt |
使用範例
範例 1:建立空白檔案
最常用的方式:一次建立一個或多個空白檔案。若檔案已存在則更新時間戳記。
$ touch README.md .gitignore
範例 2:批次建立多個檔案
搭配花括號展開一次建立多個相關檔案。
$ touch app.{py,test.py,cfg}
執行後會建立 app.py、app.test.py、app.cfg 三個空白檔案。
範例 3:更新時間戳記
對已存在的檔案執行 touch,會更新其修改時間為「現在」,常用於觸發 make 等依賴時間的工具重新建置。
$ touch Makefile
範例 4:設定特定時間戳記
使用 -d 設定檔案的時間戳記為指定日期。
$ touch -d "2026-01-01 00:00:00" archive.log
常見錯誤與排錯
touch: cannot touch 'file': Permission denied
- 原因
- 對目標目錄沒有寫入權限。
- 解法
- 使用 sudo touch,或在有寫入權限的目錄中建立檔案。