如何在Linux/Unix系统中使用touch命令创建文件和修改时间戳?

  在 Linux/Unix 系统中,touch 是一个常用的命令行工具,主要有两个功能:创建空文件修改文件时间戳。以下是详细用法指南:


一、基础用法

  1. 创建空文件

    touch filename          # 创建单个文件(若文件不存在)
    touch file1 file2 file3 # 同时创建多个文件
  2. 修改文件时间戳
    默认将文件的访问时间(access time)和修改时间(modification time)更新为当前时间:

    touch existing_file    # 文件已存在时,仅更新时间戳

二、进阶参数

参数 功能
-a 仅更新访问时间(Access Time)
-m 仅更新修改时间(Modification Time)
-c 不创建新文件(仅当文件存在时才更新时间戳)
-t 手动指定时间戳(格式:[[CC]YY]MMDDhhmm[.ss]
-r 参照其他文件的时间戳(同步时间)

三、常用场景示例

  1. 避免创建文件,仅更新时间戳

    touch -c non_existent_file  # 文件不存在则不创建
  2. 指定具体时间戳

    touch -t 202312250930.30 filename  # 设置为 2023-12-25 09:30:30
  3. 同步文件时间

    touch -r reference_file target_file  # 使 target_file 时间与 reference_file 一致
  4. 批量创建日志文件

    touch log_{2021..2023}_{01..12}.txt  # 生成 log_2021_01.txt 到 log_2023_12.txt

四、注意事项

  1. 权限问题:若目录无写入权限,touch 会报错 Permission denied
  2. 空格文件名:文件名含空格时需加引号:
    touch "my file.txt"  # 正确
    touch my file.txt # 错误(会创建 my 和 file.txt 两个文件)
  3. 时间格式:使用 -t 时需严格遵循 MMDDhhmm[.ss] 格式,例如 12250930 表示 12月25日09:30。

五、验证操作

  用 ls -l 查看文件时间戳:

ls -l filename  # 显示修改时间
ls -lu filename # 显示访问时间

  掌握 touch 后,你可以高效管理文件和时间戳!遇到问题欢迎继续提问。

留言与评论(共有 条评论)
   
验证码: