linux中修改文件atime和mtime主要用touch命令,支持-d(自然语言/标准格式)、-t(精确时间戳)和-r(复制时间戳)三种方式,且ctime由内核自动维护不可设置。

用 -d 参数设可读时间
支持自然语言和标准时间格式,适合日常使用:
- 同时设 atime 和 mtime:`touch -d "2025-12-01 09:15:30" file.txt`
- 只设访问时间:`touch -a -d "yesterday 14:00" file.txt`
- 只设修改时间:`touch -m -d "3 days ago" file.txt`
- 批量处理多个文件:`touch -d "2026-07-20 08:00" *.log`
用 -t 参数设精确时间戳
适合脚本或需要毫秒级控制的场景,格式固定为 `YYYYMMDDhhmm.ss`:
- 同步更新两个时间:`touch -t 202511221645.12 file.txt`(2025年11月22日16:45:12)
- 仅改访问时间:`touch -a -t 202508010000.00 file.txt`
- 仅改修改时间:`touch -m -t 202601011230.45 file.txt`
从另一个文件复制时间戳
省去手动输入时间,尤其适合保持时间一致性:
- 完整复制 atime 和 mtime:`touch -r ref.log target.txt`
- 只复制修改时间:`touch -m -r ref.log target.txt`
- 只复制访问时间:`touch -a -r ref.log target.txt`
- 批量应用到多个目标:`touch -r ref.log file1 file2 dir/`
其他实用细节
避免踩坑的关键点:
- -c 选项防止误建文件:`touch -c nonexistent.txt` 不会创建文件,只更新已有文件时间
- 验证结果用 stat:`stat file.txt` 查看 Access、Modify 字段是否已生效
- 注意权限限制:普通用户只能修改自己有写权限的文件;root 可修改任意文件时间戳
- ctime 不可设:无论怎么操作,文件的 Change Time 都会在 touch 执行时自动更新为当前时间











