Linux touch命令介绍
touch
命令是Linux系统中的一个标准命令,主要用于修改文件的时间戳。它的基本功能是创建新文件和更新现有文件的时间戳。如果文件不存在,touch
命令会创建一个新的空文件。
Linux touch命令适用的Linux版本
touch
命令在所有主流的Linux发行版中都可以使用,包括但不限于Debian、Ubuntu、Alpine、Arch Linux、Kali Linux、RedHat/CentOS、Fedora和Raspbian。
[linux@bashcommandnotfound.cn ~]$ touch filename
Linux touch命令的基本语法
touch
命令的基本语法如下:
touch <options> <file or directory name>
Linux touch命令的常用选项或参数说明
以下是touch
命令的一些常用选项:
选项 | 描述 |
---|---|
-a | 只修改访问时间 |
-c, --no-create | 如果文件不存在,不创建新文件 |
-d, --date | 使用日期字符串修改时间戳 |
-m | 只修改修改时间 |
-r, --reference | 将时间戳更改为参考文件的时间戳 |
-t | 修改时间戳,其中时间戳是日期/时间格式 |
Linux touch命令实例详解
以下是一些touch
命令的使用实例:
实例1:创建文件
最简单的使用touch
命令的方式是不带任何选项:
[linux@bashcommandnotfound.cn ~]$ touch filename
如果文件不存在,touch
会创建该文件。如果文件已经存在,touch
会将时间戳更改为当前时间。
实例2:创建多个文件
touch
命令也可以一次创建多个文件。要做到这一点,只需列出文件名,文件名之间用空格分隔:
[linux@bashcommandnotfound.cn ~]$ touch filename1 filename2
实例3:使用 -a 选项修改文件的访问时间
touch
命令的-a
选项可以用来修改文件的访问时间。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -a filename
这个命令会将文件的访问时间更新为当前时间,但不会改变文件的修改时间。
实例4:使用 -m 选项修改文件的修改时间
touch
命令的-m
选项可以用来修改文件的修改时间。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -m filename
这个命令会将文件的修改时间更新为当前时间,但不会改变文件的访问时间。
实例5:使用 -t 选项设置特定的时间戳
touch
命令的-t
选项可以用来设置特定的时间戳。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -t 202401251520 filename
这个命令会将文件的访问时间和修改时间都设置为2024年1月25日15点20分。
实例6:使用 -c 选项不创建新文件
touch
命令的-c
选项可以用来在不创建新文件的情况下更新现有文件的时间戳。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -c filename
如果文件不存在,这个命令不会创建新文件。如果文件已经存在,这个命令会将文件的时间戳更新为当前时间。
实例7:使用 -r 选项复制另一个文件的时间戳
touch
命令的-r
选项可以用来复制另一个文件的时间戳。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -r referencefile filename
这个命令会将filename
的时间戳设置为referencefile
的时间戳。
实例8:使用 -d 选项设置特定的日期和时间
touch
命令的-d
选项可以用来设置特定的日期和时间。以下是一个例子:
[linux@bashcommandnotfound.cn ~]$ touch -d '1 May 2024 15:20' filename
这个命令会将文件的访问时间和修改时间都设置为2024年5月1日15点20分。
Linux touch命令的注意事项
touch
命令主要用于修改文件的时间戳,而不是创建新文件。- 如果文件不存在,
touch
命令会创建一个新的空文件。 - 如果你在使用
touch
命令时看到bash: touch: command not found
的错误提示,你可能需要安装coreutils
软件包来获取touch
命令。