file 用來偵測並顯示檔案類型。它的原理不是看副檔名,而是檢查檔案開頭的「魔法數字」(magic number)與內容特徵,因此比靠擴展名猜測可靠得多。
file [-beLvz] [-f <名稱檔案>] [-m <魔法數字檔案>...] [檔案或目錄...]
-b:只列出辨識結果,不顯示檔名。-c:詳細顯示執行過程,便於除錯。-f:從指定清單檔讀取要辨識的檔名,每行一個。-L:直接顯示符號連結所指向檔案的類型。-m:指定自訂的魔法數字檔案。-v:顯示版本資訊。-z:嘗試讀取壓縮檔的內容來判斷。[root@server1 linuxeye]# file linuxeye.com linuxeye.com: ASCII text [root@server1 linuxeye]# file -b linuxeye.com # 不顯示檔名 ASCII text [root@server1 linuxeye]# file -i linuxeye.com # 顯示 MIME 類型 linuxeye.com: text/plain; charset=us-ascii
檢視符號連結時,預設只會告訴你這是個連結,加上 -L 才會追進去看真正的型別:
[root@server1 linuxeye]# ll /boot/grub/menu.lst lrwxrwxrwx 1 root root 11 Nov 9 2011 /boot/grub/menu.lst -> ./grub.conf [root@server1 linuxeye]# file /boot/grub/menu.lst /boot/grub/menu.lst: symbolic link to `./grub.conf' [root@server1 linuxeye]# file -L /boot/grub/menu.lst /boot/grub/menu.lst: ASCII text
批次辨識整個目錄,只要把星號交給它:
[root@server1 test]# file * filestat.sh: Bourne-Again shell script text executable linuxeye: directory other: ASCII text remove_duplicates.sh: Bourne-Again shell script text executable 449110BA327B23C6.vox: 8086 relocatable (Microsoft)
最後提醒一個實務上的坑:file 的判斷並非百分之百準確。上例中 .vox 檔實際應為 Dialogic VOX 格式,卻被認成 8086 relocatable,這是因為魔法數字資料庫有限,遇到罕見或自訂格式時難免失手。重要情境下仍應以實際開啟測試為準。