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: directoryFor 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 textfile 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: directoryThis is a quick way to survey an unfamiliar directory, for example after unpacking an archive.
Useful options
-b(brief) leaves out the file name.-iprints a MIME type instead of a description.-Lfollows symbolic links.
$ file -b notes.txt
ASCII text
$ file -i notes.txt
notes.txt: text/plain; charset=us-asciiOn 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
- Run
fileon/etc/passwd,/usr/bin/lsand/tmp. - Create
fake.pngas shown and check it. - Run
file -bandfile -ion 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.