Command Line · Lesson 6 of 19

file

0 / 4 checkpoints answered

Full screen ↗

In the previous lesson, you used touch to create a file without adding an extension. Linux filenames do not have to describe what a file contains: a file named funny.gif is not necessarily a GIF image.

Use the file command to inspect a file and report its likely type:

$ file banana.jpg
banana.jpg: JPEG image data

Why File Extensions Are Not Enough

Linux tools usually do not require a file extension to determine a file's type. A shell script can be named backup, a text file can be named README, and an image can have a misleading extension. The file command examines properties such as filesystem metadata and recognizable patterns in the content.

$ file README
README: ASCII text
$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable

Its result is a classification, not a guarantee. An unusual, incomplete, or damaged file may receive a broad description such as data instead of a precise type.

CheckA file named report.jpg may not contain an image. Which command checks its likely content type?

Checking Multiple Files

You can check several files at once:

$ file notes.txt image.png archive.tar.gz
notes.txt: ASCII text
image.png: PNG image data
archive.tar.gz: gzip compressed data

You can also pass a shell wildcard. The shell expands * into matching names before file examines them:

$ file *

CheckWhich command asks file to inspect every non-hidden name matched by * in the current directory?

Showing MIME Information

The -i option prints MIME-style information, including a media type and, when available, a character set. This form is useful when another program expects values such as text/html.

$ file -i index.html
index.html: text/html; charset=us-ascii

CheckWhich command reports MIME-style information for index.html?

Useful file Options

  • -i: Show MIME-style information.
  • -b: Use brief mode and omit the filename from the output.
  • -L: Follow symbolic links and classify their targets.
  • -z: Try to examine the contents of compressed files.

For example:

$ file -b notes.txt
ASCII text

CheckWhich command classifies notes.txt but omits its filename from the output?

Summary

You can now use file to investigate what a file is likely to contain.

  1. Classify a file without trusting its extension.
  2. Inspect multiple pathnames in one command.
  3. Request MIME-style information.
  4. Adjust how links, compressed data, and output labels are handled.