file 透過讀取檔案開頭的「魔數」判斷類型,而非依賴副檔名,是 Linux/Unix 系統管理與腳本撰寫的基石工具。
| 參數 | 長選項 | 說明 |
|---|---|---|
| -b | --brief | 不顯示檔名,僅輸出類型 |
| -i | --mime | 輸出 MIME 型別 (如 text/plain; charset=utf-8) |
| -z | --uncompress | 嘗試解壓縮後再檢測 (gzip/bzip2/xz) |
| -L | --dereference | 追蹤符號連結至目標檔案 |
| -f | --files-from | 從檔案讀取待檢測清單 (適合批次腳本) |
| -k | --keep-going | 繼續匹配後續規則,不在第一次匹配停止 |
| -N | --no-pad | 不對齊輸出欄位 |
| -p | --preserve-date | 保留存取時間 |
| -s | --special-files | 將區塊/字元裝置視為普通檔案檢測 |
$ file /bin/bash
/bin/bash: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=..., for GNU/Linux 3.2.0, stripped
$ file -b test.txt
UTF-8 Unicode text, with very long lines, with CRLF line terminators
$ file -i test.txt
test.txt: text/plain; charset=utf-8
$ file -z test.txt.gz
test.txt.gz: UTF-8 Unicode text, with very long lines, with CRLF line terminators (gzip compressed data, was "test.txt", from Unix, last modified: ...)
$ ln -s test.txt.gz link.gz
$ file link.gz
link.gz: symbolic link to 'test.txt.gz'
$ file -L link.gz
link.gz: gzip compressed data, was "test.txt", from Unix, last modified: ...
# 列出目錄下所有 JPEG 圖片
find . -type f -exec file -i {} + | awk -F: '$2 ~ /image\/jpeg/ {print $1}'
# 或使用 -f
find . -type f > filelist.txt
file -f filelist.txt | grep JPEG
$ file /dev/sda1
/dev/sda1: block special (8/1)
$ file /dev/tty1
/dev/tty1: character special 4/1
$ file /tmp/mysocket
/tmp/mysocket: socket
$ file /run/systemd/notify
/run/systemd/notify: socket
/usr/share/misc/magic.mgc (編譯後二進位) 或 /usr/share/file/magic/ 目錄下的文本規則。file -m /path/custom.magic 或環境變數 MAGIC。offset type operator value message,支援遞迴、位元操作、MIME 輸出。file -k 可顯示多重匹配 (如同時是 PDF 和 ZIP 的 polyglot 檔案)。file -z 配合 -k 可深度檢測巢狀壓縮 (tar.gz → tar → 內部檔案)。python-magic / libmagic 綁定可在程式中直接呼叫。