How to Determine File Types Using the file Command in Linux

In the Windows operating system, identifying a file type is incredibly simple: the system blindly trusts the three-letter file extension (like .jpg or .exe). However, the Linux kernel completely ignores file extensions. You can easily rename a malicious executable binary file to vacation_photos.txt, and Linux will not care. This creates a massive security risk when downloading unknown files from the internet. To force the operating system to mathematically analyze the internal architecture of a file and definitively prove its true identity, you must use the file command.

How the file Command Works

The file command ignores the name of the file entirely. Instead, it physically opens the file, reads the absolute first few bytes of binary data (known as the “magic numbers” or the file header), and compares those bytes against a massive, highly secure internal database to determine exactly how the data was compiled.

To use the command, simply type it followed by the file path:

file vacation_photos.txt

If the file is actually a hidden executable binary, the output will completely ignore the .txt extension and expose the truth:

vacation_photos.txt: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked

This highly technical output instantly confirms that this is not a harmless text document; it is a compiled, 64-bit ELF binary executable designed to run natively on the Linux kernel. If you attempt to open it with a text editor, it will display chaotic gibberish, but if you execute it, it could compromise your server.

Extracting MIME Types for Scripting

While the standard output is incredibly detailed for a human analyst, it is far too chaotic and verbose to be parsed by an automated bash script.

If you are writing a web server upload script that must mathematically verify if an uploaded file is a legitimate JPEG image before saving it to the hard drive, you must use the -i (MIME type) flag.

file -i profile_picture.jpg

This forces the command to strip away the verbose architectural data and output a clean, standardized, machine-readable MIME string:

profile_picture.jpg: image/jpeg; charset=binary

You can easily pipe this exact string into an awk or grep command inside your script, ensuring that your server instantly rejects any file that does not mathematically resolve to image/jpeg or image/png.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.