Skip to content

Linux Foundations / Find your way around Linux ยท Step 17 of 63

Lesson: fileSwitch
โ† Linux Foundations

Shell and files

file

Identify what a file really contains with the file command, whatever its name says.

On Linux, a file name does not have to say what is inside. A file called photo.jpg could hold plain text, and many programs have no extension at all. The file command looks at the file itself and reports what it appears to be.

Basic use

$ file notes.txt
notes.txt: ASCII text
$ file /etc
/etc: directory

For text it often reports the encoding. For programs it gives much more detail:

$ file /usr/bin/ls
/usr/bin/ls: ELF 64-bit LSB pie executable, x86-64, ...

ELF is the usual format for compiled programs on Linux. The exact wording depends on your version of file, your distribution and your processor.

Names can mislead

Rename a text file so that it looks like a picture:

$ echo "hello" > fake.png
$ file fake.png
fake.png: ASCII text

file is not fooled by the extension. It runs tests on the file: it checks what kind of filesystem object it is, then compares the bytes against a database of known patterns, often called magic numbers, and then looks for text.

Several files at once

You can pass many names, or use a wildcard that the shell expands:

$ file *
fake.png:  ASCII text
notes.txt: ASCII text
photos:    directory

This is a quick way to survey an unfamiliar directory, for example after unpacking an archive.

Useful options

  • -b (brief) leaves out the file name.
  • -i prints a MIME type instead of a description.
  • -L follows symbolic links.
$ file -b notes.txt
ASCII text
$ file -i notes.txt
notes.txt: text/plain; charset=us-ascii

On macOS the MIME option is spelled -I.

Why it helps

Check a file before you open it. Printing a binary program to the terminal can fill the screen with junk and sometimes leaves the display garbled (the reset command usually repairs it). If file says text, it is safe to read with cat or less.

Remember that the answer is an educated guess based on patterns. It is not a virus scan and does not prove a file is harmless.

If file is not found, install the package named file with your package manager.

Try it

  1. Run file on /etc/passwd, /usr/bin/ls and /tmp.
  2. Create fake.png as shown and check it.
  3. Run file -b and file -i on the same file.

Check your understanding

file

All 4 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.