Linux 不強制副檔名,file 指令透過讀取檔案頭部「魔數」精準識別類型,是管理員與開發者必備工具。
file filename
file /path/to/file
file -b filename # 僅顯示類型,不顯示檔名
file -z filename # 解壓後檢查 (支援 gzip/bzip2)
file -s /dev/sda1 # 檢查區塊裝置檔案系統類型
$ file install.log
install.log: UTF-8 Unicode text # 純文字
$ file /usr/local/
/usr/local/: directory # 目錄
$ file /bin/bash
/bin/bash: ELF 64-bit LSB executable, x86-64... # 執行檔
$ file image.png
image.png: PNG image data, 1920 x 1080... # 圖片含尺寸
$ file data.tar.gz
data.tar.gz: gzip compressed data, from Unix # 壓縮檔
file 讀取檔案前幾位元組 (Magic Number) 比對 /usr/share/misc/magic.mgc 資料庫。常見魔數:
| 檔案類型 | 魔數 (Hex) | ASCII |
|---|---|---|
| ELF 執行檔 | 7F 45 4C 46 | .ELF |
| gzip | 1F 8B | .. |
| PNG | 89 50 4E 47 0D 0A 1A 0A | .PNG.... |
| JPEG | FF D8 FF | ... |
| 25 50 44 46 | ||
| ZIP / JAR / APK | 50 4B 03 04 | PK.. |
file * | grep -v text 快速找出非文字檔file 再決定處理邏輯/etc/magic 或 ~/.magic 擴充識別規則import magic; magic.from_file('test') (需 python3-magic)mv shell.sh shell.jpg 仍是腳本-h 或 -L 控制行為善用 file,讓你看透檔案本質,不再被副檔名誤導。