Linux file Command: Identify File Types and Formats

file is a command that estimates the file type by examining not only the file extension but also the file system information, unique byte patterns in the content, and text characteristics. It can check the actual type, executable file type, character encoding, and MIME type of files with incorrect names or no extension.

This article explains everything from basic usage to MIME output, handling symbolic links and compressed files, checking multiple files, using shell scripts, and precautions when interpreting results.

What is the file command?

file inspects each path given as an argument and outputs a human-readable description of the file type.

file README.md
file photo.jpg
file /usr/bin/ls

The results may vary slightly depending on the system, file version, and magic database. A common output format is as follows.

README.md: Unicode text, UTF-8 text
photo.jpg:  JPEG image data, JFIF standard 1.01
/usr/bin/ls: ELF 64-bit LSB pie executable, x86-64, dynamically linked

file reads and categorizes the content without modifying it. However, access permission to the file is required, and access time may be updated depending on the inspection method.

How file determines the file type

A typical file implementation performs the following checks in order and uses the first successful test result as the default description.

  1. File system check: Check types such as directories, symbolic links, sockets, FIFOs, and empty files through metadata.
  2. Magic check: Compare unique byte patterns at specific locations in a file with the magic database.
  3. Text and language check: Examine character encoding and content features to estimate the text format or the language it was written in.

Files with fixed identification information in their format, such as PNG, JPEG, PDF, and ELF executables, can be classified even without an extension. In contrast, files with no unique patterns or content that is too short and ambiguous may simply be displayed as data.

Basic Syntax and Usage

file [option] file...

You can check not only a single file but multiple paths at once.

file report.pdf
file image.png archive.tar.gz script.sh
file /etc /dev/null /usr/bin/env

Paths with spaces or shell special characters should be enclosed in quotes, and use the option end marker -- before filenames that start with a hyphen.

file "annual report.pdf"
file -- -sample.bin

You can check the installed version and supported options with the following command.

file --version
file --help
man file

Compare extensions and the actual file format

Check the format even without an extension

Linux executable files or command scripts often do not have extensions. file can check the format by inspecting the content instead of the name.

file /usr/bin/bash
file /usr/bin/python3
file ./run-backup

If a script has a shebang, the interpreter information may be included in the result, and compiled programs may show the ELF format, architecture, and whether dynamic linking is used.

Check files with incorrect extensions

This is also useful when the extension of a downloaded or received file does not match the actual content.

file download.dat
file attachment.bin

Even if the result points to an image or compressed format, it does not automatically rename the file. Determine the extension after checking the necessary program and work rules.

Interpreting common results

Representative expressions Meaning
directory It is a directory, not a regular file.
symbolic link to ... It is a symbolic link pointing to another path.
empty It is an empty regular file with a size of 0 bytes.
ASCII text It is mainly text consisting of printable characters in the ASCII range.
Unicode text, UTF-8 It was determined to be Unicode text encoded in UTF-8.
ELF ... executable It is an ELF format executable file used in Linux and other systems.
shared object It may be identified as a shared library or position-independent executable format.
data It is binary data that could not be sufficiently identified as a known format or text.
cannot open The file could not be opened due to the path not existing or due to permissions, etc.

The results do not guarantee the reliability or safety of the file. The fact that it was recognized as a specific format and the judgment that it contains no malicious code are different issues.

Checking MIME type and character encoding

View MIME type and encoding together with -i

-i or --mime outputs the MIME type and character encoding instead of a long human-readable description.

file -i index.html
file --mime README.md

Text files may display the MIME type along with the charset as follows.

index.html: text/html; charset=utf-8

Output only type or encoding

--mime-type displays only the MIME type, and --mime-encoding displays only the encoding information.

file --mime-type image.webp
file --mime-encoding README.md

Use -b together if you only need the value without the filename.

file -b --mime-type image.webp
file -b --mime-encoding README.md

It can be referred to in web server settings or upload checks, but you should not judge a file as safe based solely on the MIME value sent by the client or the file result.

Adjusting the filename and spacing in output

Output description only with -b

The default output is in the format filename: description. -b or --brief omits the filename prefix.

file -b archive.tar.gz
file -b --mime-type photo.jpg

It is useful when storing only the result in a script variable.

Refining multiple file output with -N and -F

When inspecting multiple files, the filenames can be aligned to the same width. -N removes this padding, and -F changes the delimiter between the filename and the result.

file -N file1 file-with-long-name.bin
file -F ' => ' file1 file2

In automation where filenames may contain delimiters or line breaks, consider using the NUL-separated option and safe file list handling instead of directly parsing human-readable output.

Checking symbolic links

Checking the link itself

In normal default behavior, symbolic links are not followed, and both the link itself and its target are displayed. To specify this behavior, use -h or --no-dereference.

file -h current.log

Because the default behavior may vary depending on whether the POSIXLY_CORRECT environment variable is set, it is safer to specify the necessary options in scripts.

Checking link targets with -L

-L or --dereference follows symbolic links to check the actual target file's type.

file -L current.log
file --dereference latest-image

Broken links cannot open the target file, so results about the link or errors are displayed.

Check compressed files and internal data

Check compression format in the default state

If you check without options, it generally describes the outer compression format such as gzip, xz, bzip2.

file backup.tar.gz
file archive.xz

Use -z to decompress and inspect the internal format

-z or --uncompress decompresses data in supported compression formats and allows inspection of the internal contents.

file -z backup.tar.gz
file --uncompress archive.xz

The decompression process requires additional time and resources. Large files from untrusted sources or files that may be compression bombs should be handled in an isolated environment with separate restriction policies.

Check multiple files and file lists

Specify multiple files with shell glob

You can check files with a specific extension in the current directory at once.

file *.jpg
file *.sh

Depending on the shell settings, the pattern string may be passed as is if there are no files matching the glob. If there are many filenames, you may exceed the command line length limit.

Reading a list of filenames with -f

-f or --files-from reads a list of paths written one per line for checking.

file -f files-to-check.txt
file -F ' => ' -f files-to-check.txt

-f processes the list as soon as it encounters the option, so options that affect the output like -F should be placed before it.

Checking standard input and find results

Checking the data format of standard input

Specifying a single hyphen - as the filename reads data from standard input.

printf '%s\n' 'hello' | file -

Standard input can be difficult to read again, so the results may differ in detail compared to checking actual files.

Recursively checking with find -exec

To recursively check regular files including subdirectories, you can combine it with find.

find ./uploads -type f -exec file -- {} +

{} + groups found paths as much as possible and passes them to file, safely handling filenames with spaces. If there are many files to check, limit the paths and depth.

Using MIME types in shell scripts

You can receive only the MIME type without the filename and branch conditions accordingly.

path='upload.bin'
mime_type=$(file -b --mime-type -- "$path")

case "$mime_type" in
 image/jpeg|image/png|image/webp)
 printf '%s\n' 'This is a supported image format.';;
 *)
 printf '%s\n' "Unsupported format: $mime_type" >&2
 exit 1;;
esac

This check is useful for quick classification but does not replace security verification. When processing actual uploads, you should apply file size limits, safe decoders, separate storage paths, remove execution permissions, and perform malware checks as needed.

Summary of major options

Option Description
-b, --brief Omit filename prefixes in the output.
-i, --mime Prints the MIME type and character encoding.
--mime-type Prints only the MIME type.
--mime-encoding Prints only the character encoding information.
-L, --dereference Follows symbolic links to check the target file.
-h, --no-dereference Checks the link itself without following symbolic links.
-z, --uncompress Extracts supported compressed files and also checks the internal format.
-k, --keep-going Continues checking other magic matches even after the first match.
-f file Reads a list of paths to check from the specified file.
-F string Changes the delimiter between the filename and the result.
-N, --no-pad Removes the padding for sorting filenames of multiple results.
-p, --preserve-date Attempts to preserve the access time of files before checking on supported systems.
-s, --special-files Reads and checks special files such as block or character devices. Use only when understanding the risks of device access.
-E Makes file system errors terminate with an error message and failure status instead of being treated as normal results.
-- Ends option processing to safely pass filenames that start with a hyphen.

Precautions When Using file Results

The determination result is an estimate

file classifies files based on known patterns and heuristics. Damaged files, new or rare formats, or files combining multiple formats may produce ambiguous or unexpected results.

File format is different from safety

Even if identified as an image or document, it does not mean there is no malicious data inside. In security-sensitive environments, refer to the extension, MIME type, and magic determination together, and use dedicated parsers and policy-based verification.

Be careful with special files and large inputs

Reading device files with -s or checking compressed data with -z can be more risky and costly than normal file checks. Verify the source and size of the target and run with minimal privileges.

FAQ

Does the file command check file extensions?

The main detection uses file system information, content's magic patterns, character encoding, and text characteristics. Therefore, even if there is no extension or it is incorrect, the format can be inferred based on the actual content.

How can I output only the MIME type without the filename?

Use file -b --mime-type filename. -b omits the filename prefix, and --mime-type selects only the MIME type.

How can I check the file type of the target of a symbolic link?

Use file -L linkname. To check information about the link itself, use file -h linkname.

Why does the file result only show as "data"?

It may be because there is no known pattern matching the magic database and it cannot be identified as text. The file might be corrupted, too short, or the installed magic database might not recognize that format.

Related articles and official documentation

More in This Category
Linux time Command: Measure Command Execution Time

Linux time Command: Measure Command Execution Time

Learn how to use the Linux time command to measure elapsed, user CPU, and system CPU time for a command, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux history Command: Review and Reuse Shell Command History

Linux history Command: Review and Reuse Shell Command History

Learn how to use the Linux history command to review, search, reuse, and manage shell command history, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux hostnamectl Command: Show and Change the Host Name

Linux hostnamectl Command: Show and Change the Host Name

Learn how to show and Change the Host Name with the Linux hostnamectl command, including practical examples, key options, and important precautions.

Linux Tutorial / Compare Files with diff and cmp

Linux Tutorial / Compare Files with diff and cmp

Use diff and cmp to compare two files, read unified diff output, and distinguish a detected difference from an actual command error.

Linux umask Command: Control Default File Permissions

Linux umask Command: Control Default File Permissions

Learn how to control Default File Permissions with the Linux umask command, including practical examples, key options, and important precautions.

Linux diff Command: Compare Text Files and Directories

Linux diff Command: Compare Text Files and Directories

Learn how Linux diff compares text files and directories, produces unified patches, ignores selected whitespace changes, and reports differences through exit status.

Linux awk Command: Analyze Text by Fields

Linux awk Command: Analyze Text by Fields

Learn how to analyze Text by Fields with the Linux awk command, including practical examples, key options, and important precautions.

Linux join Command: Combine Files by a Common Field

Linux join Command: Combine Files by a Common Field

Learn how to combine Files by a Common Field with the Linux join command, including practical examples, key options, and important precautions.

Linux pwd Command: Print the Current Working Directory

Linux pwd Command: Print the Current Working Directory

Learn how to use the Linux pwd command to print the logical or physical absolute path of the current working directory, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux Tutorial / Install and Update Packages with APT and DNF

Linux Tutorial / Install and Update Packages with APT and DNF

Compare APT on Debian or Ubuntu with DNF on Rocky Linux for searching, installing, updating, and removing packages, including repository and transaction checks.