详解在Linux下9个有用的touch命令示例

2019-10-10 11:20:48于海丽

[root@linuxtechi ~]# touch -c sysadm-20.txt
[root@linuxtechi ~]# touch -c winadm-20.txt
[root@linuxtechi ~]# ls -l winadm-20.txt
ls: cannot access winadm-20.txt: No such file or directory

示例:5 更改文件和目录的修改时间

在 touch 命令中使用 -m 选项,我们可以更改文件和目录的修改时间。

让我们更改名为 devops.txt 文件的更改时间:

[root@linuxtechi ~]# touch -m devops.txt

现在使用 stat 命令来验证修改时间是否改变:

[root@linuxtechi ~]# stat devops.txt
 File: 'devops.txt'
 Size: 0        Blocks: 0     IO Block: 4096  regular empty file
Device: fd00h/64768d  Inode: 67324178  Links: 1
Access: (0644/-rw-r--r--) Uid: (  0/  root)  Gid: (  0/  root)
Context: unconfined_u:object_r:admin_home_t:s0
Access: 2018-03-29 23:03:10.902000000 -0400
Modify: 2018-03-29 23:59:49.106000000 -0400
Change: 2018-03-29 23:59:49.106000000 -0400
 Birth: -

同样的,我们可以改变一个目录的修改时间:

[root@linuxtechi ~]# touch -m /mnt/nfsshare/

使用 stat 交叉验证访问和修改时间:

[root@linuxtechi ~]# stat devops.txt
 File: 'devops.txt'
 Size: 0        Blocks: 0     IO Block: 4096  regular empty file
Device: fd00h/64768d  Inode: 67324178  Links: 1
Access: (0644/-rw-r--r--) Uid: (  0/  root)  Gid: (  0/  root)
Context: unconfined_u:object_r:admin_home_t:s0
Access: 2018-03-30 00:06:20.145000000 -0400
Modify: 2018-03-30 00:06:20.145000000 -0400
Change: 2018-03-30 00:06:20.145000000 -0400
 Birth: -

示例:7 将访问和修改时间设置为特定的日期和时间

每当我们使用 touch 命令更改文件和目录的访问和修改时间时,它将当前时间设置为该文件或目录的访问和修改时间。

假设我们想要将特定的日期和时间设置为文件的访问和修改时间,这可以使用 touch 命令中的 -c 和 -t 选项来实现。

日期和时间可以使用以下格式指定:

{CCYY}MMDDhhmm.ss

其中:

    CC – 年份的前两位数字 YY – 年份的后两位数字 MM – 月份 (01-12) DD – 天 (01-31) hh – 小时 (00-23) mm – 分钟 (00-59)

让我们将 devops.txt 文件的访问和修改时间设置为未来的一个时间(2025 年 10 月 19 日 18 时 20 分)。

[root@linuxtechi ~]# touch -c -t 202510191820 devops.txt

使用 stat 命令查看更新访问和修改时间:

根据日期字符串设置访问和修改时间,在 touch 命令中使用 -d 选项,然后指定日期字符串,后面跟文件名。如下所示:

[root@linuxtechi ~]# touch -c -d "2010-02-07 20:15:12.000000000 +0530" sysadm-29.txt

使用 stat 命令验证文件的状态: