file Command Cheat Sheet
The file command determines the file type. Unlike Windows, which relies on extensions (.exe, .txt), Linux uses the valid content of the file (magic numbers) to decide what it is.
Synopsis
file [OPTION...] [FILE...]
Basic Usage
Check File Type
file document.pdf
# Output: document.pdf: PDF document, version 1.4
Check Multiple Files
file *
Interpreting Scripts
It identifies shebangs to tell you the script type.
file script.py
# Output: script.py: Python script, ASCII text executable
Detailed Analysis
Show MIME Type (-i)
Useful for web servers and scripts that need the exact MIME string.
file -i image.png
# Output: image.png: image/png; charset=binary
Keep Going (-k)
Don't stop at the first match. Some polyglot files might be valid as multiple types (e.g., a ZIP file that is also a valid shell script).
file -k setup.sh
Look Inside Compressed Files (-z)
Normally, file just says "gzip compressed data". Use -z to look inside the archive.
file -z archive.tar.gz
# Output: archive.tar.gz: POSIX tar archive (gzip compressed data)
Output Options
Brief Mode (-b)
Don't print the filename, just the result. Great for scripting.
file -b myvideo.mp4
# Output: ISO Media, MP4 Base Media v1 [ISO 14496-12:2003]
Separator (-F)
Change the separator (default is :).
file -F " -> " photo.jpg
# Output: photo.jpg -> JPEG image data...
Practical Examples
Find All Executables
Combine with find to verify actual executables (ignoring permission bits).
find /bin -type f | xargs file | grep "ELF"
Verify Download Integrity
Did you download a fake image?
file suspicious.jpg
# If Output: "Bourne-Again shell script", don't open it!
Fix Broken Extensions
Renaming files based on their actual content.
for name in *; do
type=$(file -b --mime-type "$name")
case $type in
image/jpeg) mv "$name" "$name.jpg" ;;
image/png) mv "$name" "$name.png" ;;
esac
done
Magic Database
file relies on a database of "magic numbers" (signatures) located at /usr/share/file/magic (or similar).
- Compile Magic File:
file -C - Use Custom Magic File:
file -m mymagic
Exit Status
| Code | Meaning |
|---|---|
| 0 | Success |
| >0 | Error |
Notes
- Charset Detection:
file -iis one of the most reliable ways to check if a text file isutf-8,us-ascii, oriso-8859-1. - System Dependent: The detail level of descriptions depends on the
fileversion (standard is typically 5.x) and the installed magic database.