How to use the linux file command

The Linux file command tells you what a file actually is, rather than guessing from its name. It inspects the contents and reports the real type, which is especially useful in bash scripts and when you deal with files that have the wrong or missing extension. In this article, we will show you the basic usage of the Linux file command with examples.

Check a file’s type

First, pass a filename to see a short description of its contents:

file myFile.txt
# => myFile.txt: ASCII text

The description can be detailed, for example “HTML document, UTF-8 Unicode text” or “Zip archive data, at least v2.0 to extract”. This works no matter what the file extension says.

View the MIME type

Next, add the -i flag to see the MIME type instead of a plain description. This is handy when a script needs a machine-readable answer:

file -i database.sql
# => database.sql: text/plain; charset=us-ascii

Look inside a compressed file

Additionally, the -z flag tries to look inside a compressed file and report what it contains:

file -z myArchive.tar.gz

Check many files at once

Finally, you can pass several names or a wildcard to check a whole folder in one go. Add -b for a brief result that omits the filename, which is useful in scripts:

file *
file -b image.unknown

The Linux file command also works on directories, symbolic links, and special files, reporting each one for what it is. Because it only reads data, it is completely safe to run at any time, making it a quick first check before you open, download, or process an unfamiliar file. It is a small command, but it saves you from guessing and from opening the wrong thing in the wrong program.

Need more help?

Explore more Linux commands with examples on an SSH shared hosting account, or get full root control with a JetHost VPS.