Master Linux’s ‘file’ Command: From Basic Checks to Advanced Scripting
This guide explains how to use the Linux file command to identify single or multiple files, recognize text, binary, compressed, and image types, apply recursive and MIME‑output options, combine it with other utilities, and embed it in shell scripts for automation.
Basic Usage
1 View file type
The simplest use of file is to display the type of a single file. file example.txt The command returns information such as "ASCII text" or "JPEG image data".
2 Batch view file types
Use the wildcard * to check all files in the current directory. file * This lists the type of every file in the directory.
File Type Identification
1 Text files
filecan identify text files and show their character‑set encoding. file textfile.txt The output includes the file type and charset.
2 Binary files
For binary files, file usually reports "data" or "executable".
file binaryfile3 Compressed files
The command also recognises common compressed formats such as gzip, bzip2, or zip.
file compressedfile.gz4 Image files
When applied to images, file reports the format, resolution and colour depth.
file image.pngAdvanced Usage
1 Recursive view of file types
Use -r or --recursive to scan a directory tree.
file -r /path/to/directory2 Output detailed information
The -i or --mime option adds MIME type details.
file -i file.pdf3 Show only MIME type
For scripts that need just the MIME type, use -b or --brief.
file -b file.txtCombining with Other Commands
Example: locate all image files by piping find into file and grepping for "image".
find /path/to/search -type f -exec file {} \; | grep 'image'Using in Shell Scripts
#!/bin/bash
file_type=$(file -b "$1")
case "$file_type" in
"gzip compressed data")
echo "This is a gzip compressed file."
# add decompression steps
;;
"PDF document")
echo "This is a PDF file."
# add PDF handling steps
;;
*)
echo "Unknown file type."
;;
esacThis snippet demonstrates how to branch logic based on the output of file, enabling automated handling of different file types.
Conclusion
The file command is a versatile Linux utility for identifying file types, useful in everyday file management, data analysis, and automation scripts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
