一.文件的三個時間
當我們在linux中創建了文件或文件夾,文件/文件夾就有了時間屬性,而且linux中的文件具有三個時間,可以通過stat命令查看文件的三種時間:
- 訪問時間(Access time):又簡稱為atime,對文件進行一次讀操作,它的訪問時間就會改變。例如cat,more等操作,但是stat,ls命令對atime是不會有影響的。
- 修改時間(Modify time):又簡稱為mtime,文件內容最后一次修改的時間,我們經常用的ls -l命令顯示出來的文件時間就是這個時間,當對文件內容修改后,它的mtime就會相應的改變,例如vim操作。
- 改變時間(Change time):又簡稱為ctime,當文件的狀態被改變的時候,改變時間就會隨之改變。例如當使用chmod、chown等改變文件屬性的操作是會改變文件的ctime。
[root@node5 ~]# stat test.txt
File: ‘test.txt’
Size: 57 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 34566832 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2020-10-03 13:26:27.884061279 +0800
Modify: 2020-10-03 13:26:27.884061279 +0800
Change: 2020-10-03 13:26:27.884061279 +0800
#atime不會一直更新,只有當mtime更新的時候,atime才會更新
二.修改文件的三種時間為任意時間
當我們拿到一個文件,就可以隨心所欲的修改文件的三個時間。
[root@node5 ~]# ll -h test.txt
-rw-r--r-- 1 root root 57 Oct 3 13:26 test.txt
# -d, --date=字符串 使用指定字符串表示時間而非當前時間
#把test.txt文件的atime和mtime修改為20180605 21:00
[root@node5 ~]# touch -d "20180605 21:00" test.txt
[root@node5 ~]# ll -h test.txt
-rw-r--r-- 1 root root 57 Jun 5 2018 test.txt
#查看發現test.txt文件的atime和mtime已經改變,但是ctime時間沒變
[root@node5 ~]# stat test.txt
File: ‘test.txt’
Size: 57 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 34566832 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2018-06-05 21:00:00.000000000 +0800
Modify: 2018-06-05 21:00:00.000000000 +0800
Change: 2020-10-03 14:21:30.465143168 +0800
Birth: -
#change time時間只能通過修改系統時間來自定義,但是一般情況下修改系統時間需要root權限
[root@node5 ~]# date -s 06/05/2018 >> test.txt
[root@node5 ~]# stat test.txt
File: ‘test.txt’
Size: 86 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 34566832 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2018-06-05 21:00:00.000000000 +0800
Modify: 2018-06-05 00:00:00.000000000 +0800
Change: 2018-06-05 00:00:00.000000000 +0800
Birth: -
#此時發現系統時間已經改變
[root@node5 ~]# date "+%F %T"
2018-06-05 00:00:34
#現在需要更新系統時間為正常時間
[root@node5 ~]# /usr/sbin/ntpdate ntp.api.bz
3 Oct 14:39:27 ntpdate[6973]: adjust time server 114.118.7.161 offset 0.068864 sec
#系統時間已經更新正常
[root@node5 ~]# date "+%F %T"
2020-10-03 14:39:46
#系統時間已經改變,但是ctime沒變,此時文件的所有時間都已經改變
[root@node5 ~]# stat test.txt
File: ‘test.txt’
Size: 86 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 34566832 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2018-06-05 21:00:00.000000000 +0800
Modify: 2018-06-05 00:00:00.000000000 +0800
Change: 2018-06-05 00:00:00.000000000 +0800
Birth: -