042 touch命令

命令说明

touch 用于创建空文件或更新已有文件的时间戳(atime/mtime),常用于触发 make 重编译、占位标记、日志轮转测试等场景。

语法

touch [选项]... 文件...

常用参数

参数说明
-a只修改访问时间 atime
-m只修改修改时间 mtime
-c文件不存在时不创建,只改已存在文件的时间
-d 字符串按指定日期时间设置,如 -d "2025-01-01 12:00:00" 或 -d "3 days ago"
-t [[CC]YY]MMDDhhmm[.ss]按时间格式设置,如 -t 202509160830
-r 参照文件使用参照文件的时间戳
-h作用于符号链接本身而不跟随目标

使用示例

$ touch note.txt

不存在则创建空文件,存在则刷新时间戳

$ touch a.txt b.txt c.txt

一次创建多个文件

$ touch /tmp/sub/file

注意:目录不存在会报错,需先 mkdir -p

$ touch -d "2025-08-01 09:30" old.log

把文件时间改成指定日期

$ touch -r a.txt b.txt

让 b.txt 与 a.txt 时间戳一致

$ touch -t 202509160830.00 report.pdf

按 YYYYMMDDhhmm.ss 格式设置

$ touch -c exist.txt

只更新已存在文件,不创建新文件

$ touch -d "5 minutes ago" app.log

把时间回拨 5 分钟,测试日志切割脚本

实用技巧

  • touch 不截断已有文件内容,只动时间戳;想清空内容用 > file 或 truncate -s 0 file。
  • make 构建体系靠 mtime 判断是否需要重编译,touch 源文件即可强制重新构建。
  • 批量创建测试文件:touch file{1..100}.txt 或 for i in $(seq 10); do touch log.$i; done。
  • touch 创建文件受 umask 影响,默认权限 644;需要可执行要再 chmod +x。
  • ls -lu 看 atime、ls -l 看 mtime、ls -lc 看 ctime(状态改变时间,touch 改不了 ctime)。