防止创建文件
如果在 touch 后面直接跟上一个文件名,该文件如果不存在的话,将创建一个相应名字的文件。那么如果我们只想改变文件的时间戳,如果文件不存在时不进行文件创建该怎么做?这里需要加上 -c
选项。
改变Atime和Ctime
我们知道,如果不带任何选项执行 touch 命令时,文件的访问时间及修改时间都是同时被改变成当前系统时间。如下所示:
[root@localhost ~]# date
Sat Apr 20 09:42:20 CST 2019
[root@localhost ~]# touch file
[root@localhost ~]# stat file
File: ‘file’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd00h/64768d Inode: 76619361 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2019-04-20 09:42:23.954122846 +0800
Modify: 2019-04-20 09:42:23.954122846 +0800
Change: 2019-04-20 09:42:23.954122846 +0800
Birth: -
如果我们只想改变文件的访问时间,只需加上 -a
选项即可, a 即是单词 access 的缩写。
[root@localhost ~]# touch -a file
[root@localhost ~]# stat file
File: ‘file’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd00h/64768d Inode: 76619361 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2019-04-20 10:22:04.317349589 +0800
Modify: 2019-04-20 09:42:23.954122846 +0800
Change: 2019-04-20 10:22:04.317349589 +0800
Birth: -
说明,Change时间也被改了。cat 、more、 less、只会改变文件的访问时间。
改变Mtime和Ctime
如果我们只想改变文件的修改时间,只需加上 -m
选项即可, m 即是单词 modify 的缩写。
仅改变Ctime
更改文件权限,只会更改Ctime
更改为自定义时间戳
不管是不带选项,还是带上 -a
或 -m
选项,都会将文件相应的时间改为当前系统时间戳。那如果我们想改为自定义的时间戳呢?要怎么处理?否则怎么算得上时光穿梭?
我们有两种方法来更改为自定义时间戳。
1. 加上 -t
选项
比如我们将文件的时间戳改为一个将来时间:
[root@localhost ~]# touch -t 202001010101.30 file
[root@localhost ~]# stat file
File: ‘file’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd00h/64768d Inode: 76619361 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2020-01-01 01:01:30.000000000 +0800
Modify: 2020-01-01 01:01:30.000000000 +0800
Change: 2019-04-20 10:28:13.548384761 +0800
Birth: -
在这里, -t 后面所带的时间戳的格式为:
[[CC]YY]MMDDhhmm [.SS]
具体来讲,是这样的:
CC - 年份的前两位
YY - 年份的后两位
MM - 月份 [01-12]
DD - 日期 [01-31]
hh - 时 [00-23]
mm - 分 [00-59]
SS - 秒 [00-61]
2. 加上 -d
选项
我们再用新方法将文件的时间戳改成一个过去的时间(2008年奥运会开幕式):
[root@localhost ~]# touch -d '08-August-2008' file
[root@localhost ~]# stat file
File: ‘file’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd00h/64768d Inode: 76619361 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2008-08-08 00:00:00.000000000 +0800
Modify: 2008-08-08 00:00:00.000000000 +0800
Change: 2019-04-20 10:31:47.103405103 +0800
Birth: -
在这里,时间的格式为:日-月-年
。但是,这里的时间可以相当灵活,比如也支持 yesterday
、 1 year ago
等等模糊时间:
[root@localhost ~]# touch -d 'yesterday 08-August-2008' file
[root@localhost ~]# stat file
File: ‘file’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: fd00h/64768d Inode: 76619361 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2008-08-07 00:00:00.000000000 +0800
Modify: 2008-08-07 00:00:00.000000000 +0800
Change: 2019-04-20 10:32:57.041411765 +0800
Birth: -
总结:Ctime时间,只要访问时间,修改时间,或文件权限有一个修改,Ctime时间都会修改