How to Use the file Command to Determine File Types in Linux

In Windows environments, the operating system relies almost entirely on a file’s extension (like .jpg, .exe, or .txt) to determine what kind of file it is and how to open it. If you rename a photo from image.jpg to image.txt, Windows will become confused and try to open the photo in Notepad. Linux, however, does not care about file extensions. A file can have no extension at all, and Linux will still know exactly how to handle it. If you ever encounter a mystery file with no extension on a Linux system, you can use the file command to instantly reveal its true identity.

How the file Command Works

The file command ignores the name of the file entirely. Instead, it reads the actual binary data inside the file (specifically looking at the “magic number” headers at the very beginning of the data stream). By comparing these internal signatures against a vast, system-wide database of known file types, it can accurately identify almost anything.

Basic Usage: Identifying a Mystery File

If you have a file named mystery_data and you have no idea if it is a script, a compressed archive, or a database, simply run the command followed by the filename.

file mystery_data

The command will output the file name, followed by a colon, and then a human-readable description of exactly what is inside. For example:

mystery_data: PNG image data, 1920 x 1080, 8-bit/color RGBA, non-interlaced

Even though the file lacks a .png extension, the file command successfully looked inside the data stream, recognized the PNG header, and even extracted the image resolution.

Checking Multiple Files at Once

You can identify multiple files simultaneously by using wildcards. If you have a directory full of random, extension-less files downloaded from a server, you can identify all of them at once:

file *

The output will list every file in the directory, clearly identifying which ones are ASCII text, which are gzip compressed archives, and which are ELF (Executable and Linkable Format) binaries.

Extracting Just the MIME Type (For Scripts)

While the human-readable description is great for manual troubleshooting, it is often too verbose for automated bash scripts. If you are writing a script that needs to sort files based on their type, you can use the -i (or --mime-type) flag.

file -i mystery_data

Instead of a long descriptive sentence, the command will output the strict, standardized MIME type and charset, which is much easier to parse in an if/else statement:

mystery_data: image/png; charset=binary

Get the best tech tips delivered straight to your inbox.

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