萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux stat 命令深度解析:inode 元數據、三時間語義、格式化輸出與文件系統屬性

stat vs ls:信息維度對比

一、基礎輸出解讀

$ stat test.sh
  File: test.sh
  Size: 109          Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d Inode: 1234567     Links: 1
Access: (0755/-rwxr-xr-x)  Uid: ( 1000/ user)   Gid: ( 1000/ user)
Access: 2024-01-15 10:30:45.123456789 +0800
Modify: 2024-01-14 22:15:20.000000000 +0800
Change: 2024-01-14 22:15:20.000000000 +0800
 Birth: -

三時間語義(核心概念)

命令顯示信息
ls -l權限、鏈接數、擁有者、大小、修改時間、文件名
stat上述全部 + inode、設備號、塊大小、訪問/修改/狀態變更時間(納秒精度)、SELinux 上下文、文件系統屬性

關鍵區別: 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

常用格式化符號速查表

時間英文觸發條件ls 參數
Access Timeatime讀取文件內容(cat、vim 只讀)ls -lu
Modify Timemtime修改文件內容(echo >、vim 保存)ls -l
Change Timectime修改元數據(chmod、chown、mv、ln)ls -lc

三、文件系統屬性查看(-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
符號含義
%n文件名
%iinode 號
%s字節大小
%b/%B分配塊數 / 塊大小
%a/%A八進制權限 / 符號權限
%u/%UUID / 用戶名
%g/%GGID / 組名
%x/%Xatime 人類/秒
%y/%Ymtime 人類/秒
%z/%Zctime 人類/秒
%F文件類型
%CSELinux 上下文