小小白祈祷中...

touch 是 Linux/Unix 系统中用于创建空文件或更新文件时间戳的命令。它是一个简单而常用的工具,特别适合文件操作时快速创建新文件或修改现有文件的时间信息。


基本语法

1
touch [选项] 文件名
  • 选项:控制行为(如修改时间戳、创建文件等)。
  • 文件名:指定需要操作的目标文件,可以是一个或多个。

常用功能

创建空文件

如果文件不存在,touch 会创建一个新的空文件。

1
touch 文件名
  • 示例
1
touch example.txt
  • 作用:创建一个名为 example.txt 的空文件。

批量创建多个文件

可以同时创建多个文件。

1
touch 文件1 文件2 文件3
  • 示例
1
touch file1.txt file2.txt file3.txt
  • 作用:创建 file1.txtfile2.txtfile3.txt

更新文件的时间戳

如果文件已存在,touch 会更新该文件的 访问时间(atime)修改时间(mtime)

1
touch 文件名
  • 示例
1
touch existing_file.txt
  • 作用:更新 existing_file.txt 的时间戳为当前时间。

指定时间戳

使用 -t 选项可以设置自定义的时间戳。

1
touch -t [[CC]YY]MMDDhhmm[.ss] 文件名
  • 格式说明:

    • CC:世纪(可选)。
    • YY:年。
    • MM:月(01-12)。
    • DD:日(01-31)。
    • hh:小时(00-23)。
    • mm:分钟(00-59)。
    • .ss:秒(可选,00-59)。
  • 示例

1
touch -t 202312312359.59 example.txt
  • 作用:将 example.txt 的时间戳设置为 2023 年 12 月 31 日 23:59:59。

使用参考文件的时间戳

可以使用 -r--reference 选项以其他文件的时间戳为参考。

1
touch -r 参考文件 文件名
  • 示例
1
touch -r old_file.txt new_file.txt
  • 作用:将 new_file.txt 的时间戳设置为与 old_file.txt 相同。

不创建文件,仅修改时间戳

使用 -c--no-create 选项可以避免创建新文件,仅更新已有文件的时间戳。

1
touch -c 文件名
  • 示例
1
touch -c existing_file.txt
  • 作用:更新 existing_file.txt 的时间戳,如果文件不存在,则不创建。

修改访问时间或修改时间

1) 仅修改访问时间(atime)

使用 -a 选项可以只更新访问时间。

1
touch -a 文件名
  • 示例
1
touch -a example.txt
  • 作用:仅更新 example.txt 的访问时间,保持修改时间(mtime)不变。

2) 仅修改修改时间(mtime)

使用 -m 选项可以只更新修改时间。

1
touch -m 文件名
  • 示例
1
touch -m example.txt
  • 作用:仅更新 example.txt 的修改时间,保持访问时间(atime)不变。

检查文件时间信息

虽然 touch 不直接显示文件时间信息,但可以使用 ls -l 查看文件的修改时间,或使用 stat 查看详细的时间信息。

1) 查看修改时间

1
ls -l 文件名
  • 示例
1
ls -l example.txt
  • 输出:显示文件的修改时间。

2) 查看详细时间信息

1
stat 文件名
  • 示例
1
stat example.txt
  • 输出:显示文件的访问时间(atime)、修改时间(mtime)和状态更改时间(ctime)。

常用选项总结

选项 作用
-a 仅更新访问时间(atime)。
-m 仅更新修改时间(mtime)。
-c--no-create 不创建新文件,仅修改已有文件的时间戳。
-r--reference 使用参考文件的时间戳。
-t 指定自定义时间戳(格式:[[CC]YY]MMDDhhmm[.ss])。

示例场景

创建多个文件

1
touch file1.txt file2.txt file3.txt
  • 作用:同时创建 file1.txtfile2.txtfile3.txt

更新文件时间戳

1
touch existing_file.txt
  • 作用:更新 existing_file.txt 的时间戳为当前时间。

修改文件为特定时间戳

1
touch -t 202312312359.59 file.txt
  • 作用:将 file.txt 的时间戳设置为 2023 年 12 月 31 日 23:59:59。

模拟文件访问

如果需要模拟文件被访问的行为,可以只更新文件的访问时间。

1
touch -a file.txt

复制时间戳

将一个文件的时间戳复制到另一个文件。

1
touch -r source_file.txt target_file.txt

避免创建新文件

如果不希望 touch 创建新文件,可以使用 -c 选项。

1
touch -c file_does_not_exist.txt
  • 作用:如果 file_does_not_exist.txt 不存在,则什么都不做。

注意事项

  1. 没有权限:如果对目标文件或目录没有写权限,则 touch 命令会失败。
  2. 文件已存在touch 不会覆盖文件内容,仅更新时间戳。
  3. 批量操作:可以在命令中一次性操作多个文件,例如批量创建文件或批量更新文件时间。

总结

操作 命令
创建空文件 touch 文件名
创建多个文件 touch 文件1 文件2 文件3
更新文件时间戳 touch 文件名
仅更新访问时间 touch -a 文件名
仅更新修改时间 touch -m 文件名
设置特定时间戳 touch -t 时间戳 文件名
使用参考文件时间戳 touch -r 参考文件 目标文件
不创建新文件 touch -c 文件名

touch 是一个快速、灵活的文件操作工具,尤其在脚本和系统自动化任务中非常有用!