Command line tip - determine a file’s type with file

  • August 28, 2007
  • Avatar for peter
    Peter
    Upfold

Unlike some popular operating systems you might know of, Linux is clever enough to actually look inside the contents of a file and not just its extension (if any) to work out what type a file is.

This functionality isn't just hidden away - if you want to quickly peek at a file's type, or you have a binary file that you want to try and identify, you can use the command line tool file to use this same technology to discover a filetype.

It is frighteningly simple to use - simply give file the location of the target file to test. For example:

$ file /bin/bash

In this case, we're examining /bin/bash, which we already know is an executable file. On my system, the result looks like this:

/bin/bash: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.0, dynamically linked (uses shared libs), stripped

As you can see - wherever possible, file will give detailed information. For example, here I check out a PNG image:

$ file cygwin.png
cygwin.png: PNG image data, 207 x 207, 8-bit/color RGBA, non-interlaced

And a PDF:

$ file Silent.pdf
Silent.pdf: PDF document, version 1.4

This method isn't perfect and there are occasions when it can incorrectly identify files (for example, it can't work out what OpenDocument files are as they are also completely valid Zip archives), so don't rely on it for critical things.

If you want to quickly discover a filetype and you're already in the command line however, file is a very useful tool which should be in your CLI toolkit!

Avatar for peter Peter Upfold

Home » Articles »