| 時間 | 英文 | 觸發條件 | ls 參數 |
| Access Time | atime | 讀取文件內容(cat、vim 只讀) | ls -lu |
| Modify Time | mtime | 修改文件內容(echo >、vim 保存) | ls -l |
| Change Time | ctime | 修改元數據(chmod、chown、mv、ln) | ls -lc |
關鍵區別: mtime 變更必然導致 ctime 變更,但 ctime 變更不一定伴隨 mtime 變更(如僅 chmod)。atime 頻繁更新影響性能,生產環境常掛載 noatime 或 relatime。
二、格式化輸出(--format / --printf)
腳本解析首選,支持完整格式化字符串:
# 文件類型
stat --format=%F test.sh # regular file / directory / symbolic link
# 硬鏈接數
stat --format=%h test.sh # 1
# 權限:八進制 / 人類可讀
stat --format=%a test.sh # 755
stat --format=%A test.sh # -rwxr-xr-x
# SELinux 上下文
stat --format=%C test.sh # unconfined_u:object_r:user_home_t:s0
# 時間:人類可讀 / Epoch 秒
stat --format=%x test.sh # 2024-01-15 10:30:45.123456789 +0800
stat --format=%X test.sh # 1705285845
# inode 與設備
stat --format=%i test.sh # 1234567
stat --format=%d test.sh # 64768 (十進制設備號)
# 組合輸出
stat --format="%n: inode=%i, size=%s, mtime=%Y" test.sh
常用格式化符號速查表
| 符號 | 含義 |
| %n | 文件名 |
| %i | inode 號 |
| %s | 字節大小 |
| %b/%B | 分配塊數 / 塊大小 |
| %a/%A | 八進制權限 / 符號權限 |
| %u/%U | UID / 用戶名 |
| %g/%G | GID / 組名 |
| %x/%X | atime 人類/秒 |
| %y/%Y | mtime 人類/秒 |
| %z/%Z | ctime 人類/秒 |
| %F | 文件類型 |
| %C | SELinux 上下文 |
三、文件系統屬性查看(-f)
stat -f /dev/sda2
File: "/dev/sda2"
ID: 0 Namelen: 255 Type: ext2/ext3
Block size: 4096 Fundamental block size: 4096
Blocks: Total: 259366 Free: 259337 Available: 259337
Inodes: Total: 223834 Free: 223531
適用於腳本獲取文件系統剩餘空間、inode 使用率、最大文件名長度等。
四、通配符批量查看
stat /etc/passwd /etc/group /etc/shadow
stat myfile* # 支持 shell 通配符展開
五、實戰場景
- 審計文件變更: 對比 mtime/ctime 判斷是內容變更還是屬性變更
- 排查備份差異: stat --format=%Y 獲取秒級 mtime,配合 rsync --checksum
- 檢測掛載點: stat -f 確認設備號變化判斷是否重新掛載
- 容器環境: stat /proc/1/ns/mnt 獲取命名空間 inode 對比隔離性
總結
stat 是文件元數據的「CT 掃描」。掌握 atime/mtime/ctime 語義區別、--format 格式化輸出、-f 文件系統屬性 三大核心用法,即可在腳本、審計、故障排查中游刃有餘。注意:Birth time(創建時間)Linux 歷史不支持,ext4/xfs 近期內核開始支持(stat 顯示 Birth 行)。
copyright ©
萬盛學電腦網 all rights reserved