约 4889 字

约 24 分钟

#Bash 的 touch 命令

touch [OPTION]... FILE...

功能

将文件的时间戳修改为当前时间,如果文件不存在则会创建一个空文件。

类型

可执行文件(/usr/bin/rm),属于 coreutils。

参数

  • OPTION 选项:
    • -a - 只修改文件的访问时间(access time)
    • -c, --no-create - 不创建文件
    • -d, --date=STRING - 指定时间(格式为 YYYY-MM-DD HH:MM:SS),而不是当前时间
    • -f -
    • -h, --no-dereference - 如果文件是符号链接,修改符号链接本身,而不是源文件
    • -m - 只修改文件的修改时间(modification time)
    • -r, --reference=FILE - 使用 FILE 文件的时间
    • -t STAMP - 指定时间(格式为 [[CC]YY]MMDDhhmm[.ss]),而不是当前时间
    • --time=WORD - 修改指定的时间类型;有效值:atime, mtime
    • --help - 显示帮助
    • --version - 显示版本
  • FILE - 文件列表

#示例

更新已有文件的时间戳

$ touch existing.txt
  • 默认更新 访问时间 + 修改时间 为当前时间。

创建新文件(如果不存在)

$ touch file.txt
  • 如果 file.txt 不存在,则创建空文件。

不创建新文件(仅修改已有文件)

$ touch -c file.txt
  • 文件不存在时不创建

只更新访问时间(atime)

$ touch -a file.txt

只更新修改时间(mtime)

$ touch -m file.txt

设置指定时间

$ touch -t 202510271200 file.txt
  • 修改时间为 2025-10-27 12:00
$ touch --date="2025-10-27 12:00" file.txt
  • 使用可读时间字符串(GNU 扩展)

参考另一个文件的时间

$ touch -r file1 file2
  • 让 file2 的时间和 file1 一样
$ touch -r file1 --time=atime file2   # 只修改访问时间
$ touch -r file1 --time=mtime file2   # 只修改修改时间
  • 可以指定修改哪个时间戳

修改多个文件的时间

$ touch file1.txt file2.txt file3.txt

#推荐阅读

#手册

更新: 2026/1/18

作者: PlanC

创建: 2025/10/27