touch 命令最基本的功能就是创建空文件,touch 还能更改文件的时间戳、修改时间等。

常用参数

参数 意义
-a 只更改最后访问时间
-c, –no-create 不创建任何文件
-d, –date = 字符串 使用指定字符串表示时间而非当前时间
-m 只更改修改时间

示例

1. 使用 touch 命令创建一个空文件

touch 命令最简单和最基本的用法是通过命令行创建一个空文件

1
touch 

2. 使用 touch 命令一次创建多个文件

尽管 cat 命令和标准重定向符号也是通过命令行创建文件的方法,但 touch 命令具有优势,因为您可以一次创建多个文件。 您可以使用以下语法通过 touch 命令创建多个文件:

1
touch test1 test2 test3

3. 强制避免使用 touch 命令创建新文件

有时,如果新文件不存在,则需要避免创建新文件。 在这种情况下,您可以使用 touch 命令使用’-c’选项,如下所示:

1
touch -c “filename”

4. 更改文件的访问和修改时间

touch 命令的另一个用途是更改文件的访问时间和修改时间。

1
touch linuxmi

此 touch 命令将访问和修改时间更改为再次为 运行 touch 命令的时间

5. 更改访问时间或修改时间

可以选择仅通过 touch 命令更改其中一个,而不是更改访问和修改时间。

touch 命令使用’-a’选项来仅更改此文件的访问时间:

1
touch -a test

touch 命令使用’-m’选项仅更改此文件的修改时间:

1
touch -m test

6. 将访问和修改时间从一个文件复制到另一个文件

如果要将 test1 的访问和修改时间更改为 test2 的访问和修改时间,可以使用如下 touch 命令:

1
touch test1 -r test2

7. 使用指定的时间戳创建新文件

创建具有指定时间戳的新文件

1
touch -t 2006151230.30 test
1
touch -d 20240423 test

8. 将文件的时间戳更改为其他时间

您可以使用 touch 命令的以下语法将现有文件的时间戳更改为其他时间:

1
$ touch -c -t YYMMDDHHMM.SS “filename”
1
touch -c -t 2008191130.30 linuxidc