touch 是 Linux/Unix 系统中最基础、最常用的命令之一。它的核心功能是修改文件或目录的时间戳,而在文件不存在时,则会默认创建一个新的空文件。
很多 Linux 命令,如 find 或 make,依赖文件的时间戳来判断文件是否"新"。因此,touch 在脚本自动化、备份同步和编译管理等场景中,是一个非常重要的工具。
📖 命令与文件时间戳
在使用 touch 前,需要先了解 Linux 文件的三种时间戳:
- 访问时间 (Access Time, atime)
- 含义 :文件内容最后被读取的时间。使用 cat、less 或 grep 命令读取文件内容时更新。
- 查看方式 :ls -lu。
- 修改时间 (Modify Time, mtime)
- 含义 :文件内容最后被修改的时间。这是 touch 默认更新的时间。
- 查看方式 :ls -l (默认显示)。
- 更改时间 (Change Time, ctime)
- 含义 :文件元数据(如权限、所有者) 最后被修改的时间。
- 查看方式 :ls -lc。
需要注意的是,ctime 由系统自动维护,当文件状态发生变化时(例如更改权限、重命名或通过 touch 修改了 atime 或 mtime),ctime 都会更新为当前时间,无法用 touch 命令直接修改。
📝 命令基本语法
touch 的基本语法是:
bash
touch [选项]... [文件名]...
🔧 常用选项详解
touch 提供了多种选项来控制其行为,具体如下表所示:
| 选项 | 功能说明 | 使用示例 |
|---|---|---|
| -a | 只更改文件的 访问时间 (atime)。 | touch -a existing.txt |
| -m | 只更改文件的 修改时间 (mtime)。 | touch -m existing.txt |
| -c | 如果文件不存在,则不创建新文件。 | touch -c nofile.txt |
| -d | 使用指定的日期时间字符串,而非当前时间。 | touch -d "2025-01-01 12:00:00" myfile.txt |
| -t | 使用指定格式 [[CC]YY]MMDDhhmm[.ss] 的时间。 | touch -t 202501011200.00 myfile.txt |
| -r | 将文件的时间戳设置为与参考文件相同。 | touch -r reference.txt target.txt |
| -h | 影响符号链接本身的时间戳,而非其指向的文件。 | touch -h symlink |
💡 实用示例
1.创建新文件
bash
#创建一个名为file.txt的空文件
touch file.txt
2.批量创建多个文件
bash
#方法1:直接列出所有文件名
touch file1.txt file2.txt file3.txt
#方法2:使用花括号扩展创建一系列文件(如file1.txt到file10.txt)
touch file{1..10}.txt
3.只更新文件的访问时间 ( -a**)**
bash
#假设文件已存在,只更新其atime
touch -a existing-file.log