touch
touch 的本职是修改文件的时间戳,文件不存在时顺带创建一个空文件 —— 后面这个副作用反倒成了它最常见的用途。
touch [选项] 文件...不带选项时把 atime 和 mtime 都设成当前时间 文件已存在不会清空内容,只动时间戳;要清空用
> file
文件的元数据里记着三个时间戳,touch 能改的只是其中两个:
| 时间戳 | 含义 | 查看 |
|---|---|---|
| atime | 最后一次读取内容的时间(access) | ls -lu、stat |
| mtime | 最后一次修改内容的时间(modify) | ls -l、stat |
| ctime | inode 最后一次变动的时间(change),权限、属主、链接数变了都算 | ls -lc、stat |
touch 能改 atime 和 mtime,改不了 ctime 恰恰相反,任何一次 touch 都会把 ctime 刷成当前时间 —— 改时间戳本身就是一次 inode 变动
| 选项 | 说明 |
|---|---|
-a |
只改 atime |
-m |
只改 mtime |
-c |
文件不存在时不要创建(no-create) |
-d <时间> |
用可读的时间字符串,如 "2024-01-01 08:00"、"-2 days" |
-t <时间> |
用 [[CC]YY]MMDDhhmm[.ss] 格式,如 202401010800 |
-r <文件> |
把时间戳对齐到另一个文件(reference) |
-h |
目标是软链接时改链接自身,不跟随到目标文件 |
1. 创建空文件
touch a.txttouch a.txt b.txt c.txttouch file{1..5}.txt花括号由 shell 展开,见 glob
2. 指定时间
touch -d "2024-01-01 08:00" a.txttouch -d "-2 hours" a.txttouch -t 202401010800 a.txt
-d接受相对时间,-t只认固定格式的数字串
3. 对齐到另一个文件
touch -r ref.txt a.txt常用于让一批文件的时间戳保持一致
4. 只刷时间,不创建
touch -c maybe.txt脚本里刷新已有文件的时间戳时加上
-c,避免路径写错造出一堆空文件
5. 强制重新编译
touch main.c && makemake 靠比较源文件和目标文件的 mtime 决定要不要重建,touch 一下源文件就能强制触发一次,见 make
man touch- GNU Coreutils – touch