Linux File Command: How to Determine File Type in Linux
The Linux file command helps determine the type of a file and its data. The command doesn’t take the file extension into account, and instead runs a series of tests to discover the type of file data.
In this tutorial, we will show you how the file command works and how to use it.
- A system running Linux.
- Access to the terminal window.
File Command Syntax
The file command uses the following basic syntax:
In the syntax above, file name represents the name of the file you want to test. The file command performs three sets of tests trying to determine the file type, in this order:
- Filesystem tests perform a stat(2) system call and check the result against the system header file. This way, the file command determines if the file is a common type for your system (such as a text file, image, directory, etc.).
- Magic tests use a short string of numbers stored near the beginning of the file («magic number») to test if the file is a binary executable and, if so, determine its type. The information needed to perform these tests is stored in /etc/magic or /usr/share/misc/magic from a compiled magic file.
- Language tests use a special tag to determine which programming language a binary executable file is written in.
The command output provides a short description of the file and data type. For instance, using the file command to test a text file:
File Command Options
The file command uses the following options:
Test All Files in a Directory
Add a wildcard character ( * ) to the file command to test all the files and directories in the current working directory:
Add the path to a directory to the wildcard character to test the contents of that directory:
For instance, to test the contents of the Example directory, use:
Test Files in a Range
The file command lets you test a subset of files in a directory using Regex-style ranges. Select a range by placing the values in brackets. For instance, testing files and directories with names in the a-l range:
Since Regex-style ranges are case-sensitive, the output in the example above only shows file types for files starting with lowercase a-l. Adding another range lets you include uppercase characters as well:
Test Files from a List
The file command lets you use a text file as a list of files to test. The text file must only contain one file name per line.
Use the -f option and add the path to the list file to file command:
Test Special Files
The file command is not always able to read special files, such as system files:
In the example above, the file command output shows that /dev/sda5 is a block special file but doesn’t offer additional details. Using the -s option lets you fully test special files:
Note: If you are not logged in as the root user, attempting to test a special file results in a no read permission error message. Add sudo to the file command to prevent this.
Test Compressed Files
Use the -z option to fully test compressed files, trying to detect their content:
Test Parsed Version of File
Using the -c option displays the check printout for the parsed version of the file:
This option is usually used with the -m option to debug and install a new magic file.
Display Brief Output
Using the -b option displays the brief version of the output. This version of the output only shows file types and omits file names.
Add Separators to Output
Using the -F option lets you define a character that acts as a separator between the file name and file type sections of the output. For instance, add a plus sign ( + ) as a separator with:
Remove File Name Padding from Output
Use the -N option to remove the padding between the file name and file type sections of the output:
The resulting output is no longer vertically aligned:
After reading this tutorial, you should be able to use the Linux file command to find out the types of files on your system.
If you’re interested in learning more about Linux commands, have a look at our Linux commands cheat sheet.
Как узнать типы файлов в Linux
Самый простой способ определить тип файла в любой операционной системе — обычно посмотреть на его расширение (например, .xml, .sh, .c -f , как показано ниже.
3. Чтобы файл работал быстрее, вы можете исключить тест (действительные тесты включают тип приложения, ascii, кодировку, токены, cdf, сжатие, эльф, софт и tar) из списка тестов, выполненных для определения тип файла, используйте флаг -e , как показано ниже.
4. Параметр -s заставляет файл также читать блочные или символьные специальные файлы, например.
5. Добавление параметров -z указывает файлу искать внутри сжатых файлов.
6. Если вы хотите сообщить информацию только о содержимом, а не о сжатии сжатого файла, используйте флаг -Z .
7. Вы можете указать команде файла выводить строки типа mime вместо более традиционных, удобочитаемых человеком, используя параметр -i .
8. Кроме того, вы можете получить разделенный косой чертой список допустимых расширений для найденного типа файла, добавив переключатель –extension.
Для получения дополнительной информации и вариантов использования обратитесь к справочной странице file command.
Вот и все! команда file — полезная утилита Linux для определения типа файла без расширения. В этой статье мы поделились некоторыми полезными примерами файловых команд. Если у вас есть какие-либо вопросы или мысли, чтобы поделиться, используйте форму обратной связи ниже, чтобы связаться с нами.
Команда file в Linux
Команда file — одна из самых полезных, поскольку позволяет узнать тип данных, которые на самом деле содержатся внутри документа. Если у вас есть какой-либо файл, взятый из ненадёжного источника, не поленитесь проверить его с помощью этой команды, прежде чем нажать кнопку Открыть. Возможно, такая предосторожность покажется лишней, но она оградит вас от «встречи» с нежелательным контентом.
В большинстве дистрибутивов Linux утилита file (работу которой и запускает одноимённая команда) входит в стандартный набор программного обеспечения.
Синтаксис и опции file
Синтаксис команды file достаточно простой. Записывать её в эмуляторе терминала или консоли следует так:
file опции название_документа
Что же касается опций, то их у этой команды несколько десятков. Мы рассмотрим лишь основные:
- -b, —brief — запрет на демонстрацию имен и адресов файлов в выводе команды;
- -i, —mime — определение MIME-типа документа по его заголовку;
- —mime-type, —mime-encoding — определение конкретного элемента MIME;
- -f, —files-from — анализ документов, адреса которых указаны в простом текстовом файле;
- -l, —list — список паттернов и их длина;
- -s, —special-files — предотвращение проблем, которые могут возникнуть при чтении утилитой специальных файлов;
- -P — анализ определенной части файла, которая обозначается различными параметрами;
- -r, —raw — отказ от вывода /ooo вместо непечатных символов;
- -z — анализ содержимого сжатых документов.
Для того, чтобы ознакомиться с полным списком опций, выполните в терминале команду:
Примеры использования file
Если вам нужно всего лишь посмотреть тип файла, использовать опции не обязательно. Достаточно прописать имя команды, а также название файла и путь к нему, при условии, что он находится не в корневой папке:
Случается, что нужно проверить не один, а несколько файлов. Чтобы не выполнять команду много раз подряд, перечисляйте названия всех файлов через пробел:
file /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Как видно на примере, картинки с расширениями gif и tiff в действительности оказались текстовыми документами, а архив с расширением zip — PDF документом. Кстати, команда file даёт возможность не только проверить, является ли архив архивом, но и заглянуть внутрь, чтобы узнать, что в нём содержится. Для этой цели используется опция -z:
file -z /home/main-user/losst/testarchive.zip
Как вы успели заметить, команда, возвращая ответ, постоянно выводит названия файлов, что в некоторых случаях бывает удобно, но зачастую только усложняет чтение результатов. Отключить эту функцию легко — воспользуйтесь опцией -b:
file -b /home/main-user/losst/test-file.gif /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Иногда нужно узнать не просто тип файла, а его MIME-тип. В таком случае на помощь приходит опция -i:
file -i -b /home/main-user/losst/fileA.sbin /home/main-user/losst/fileG.aspx /home/main-user/losst/fileH.lua
Нередко по каким-либо причинам утилита не может найти указанный файл: например, вы ошиблись буквой в его названии или неверно указали папку, в которой он находится. Тогда вывод информации об этом файле предваряет фраза cannot open. Впрочем, есть возможность видоизменить результат, добавив в него сообщение об ошибке. Для этого используйте опцию -E.
Сравните вывод команды с опцией -E и без неё:
file -E -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
file -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
Еще один способ работы с утилитой file — запись названий и адресов документов в простой текстовый файл. Применяя этот способ на практике, не забывайте добавлять к команде опцию —files-from, после которой указывайте имя файла, содержащего список документов, и путь к нему.
file —files-from /home/main-user/losst/list_of_files.txt
Выводы
Команда file помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
4 Ways to check file type in Linux
In Linux, there are a few different ways that you can check the type of a file. This is helpful if you want to determine what program to use to open the file, or if you just want to know more about the file itself.
In this blog post, we will discuss four different methods that you can use to check file type in Linux. We will also provide instructions on how to easily identify a file’s format!
understanding file type in Linux
Most filesystem implementations define seven types of files. Even when developers add something new and wonderful to the file tree (such as the process information under /proc), it must still be made to look like one of these seven types:
- Regular files
- Directories
- Character device files
- Block device files
- Local domain sockets
- Named pipes (FIFOs)
- Symbolic links
The most common file types are regular files and directories.
Regular files
Regular files consist of a series of bytes; filesystems impose no structure on their contents. Text files, data files, executable programs, and shared libraries are all stored as regular files. Both sequential access and random access are allowed.
You can use touch, cat or echo commands to create files in Linux.
Directories
A directory contains named references to other files. You can create directories with mkdir and delete them with rmdir if they are empty. You can recursively delete nonempty directories—including all their contents—with rm -r.
The special entries “.” and “..” refer to the directory itself and to its parent directory; they cannot be removed. Since the root directory has no real parent directory, the path “/..” is equivalent to the path “/.” .
Procedure to check file type in Linux
- Open the terminal and navigate to the directory where the file is located.
- Type in the command stat -c “%F” filename to check the file type.
- press enter to run the command
- The file type will be listed on the command output
Check file type with stat command in Linux
The easiest way to check file type in Linux is using stat command. To use this method, you will need to open up a terminal window and change into the directory where the file is located. Once you are in the correct directory, you will need to type the following command: stat filename
The output of stat command in Linux can be a little confusing if you are not familiar with it. Here is a breakdown of what each column in the output means:
File: test
Size: 9 Blocks: 8 IO Block: 4096 regular file
Device: fd06h/64774d Inode: 6291591 Links: 1
Access: (0600/-rw——-) Uid: (50290/ocp) Gid: (50290/ocp)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2022-09-15 13:38:55.788502818 +0000
Modify: 2022-09-15 13:38:55.788502818 +0000
Change: 2022-09-15 13:38:55.788502818 +0000
Birth: —
- Access: This column displays the permissions for the file.
- Inode: This is the unique identifier for the file.
- Device: This column displays the device name of the file system where the file is located.
- Size: This column displays the size of the file in bytes.
- Blocks: This column displays the number of blocks that are allocated to the file.
From this information, you can see that the Type column displays the type of file, which in this case is a regular text file. You can also see that the Size column displays the size of the text file, which is 9 bytes.
The stat command with -c option allows you to use a particular or custom format instead of the default, it prints a newline after each use of the format sequence.
stat -c «%F» filename
If you want more information about the stat command and what it can do, you can type the following command: man stat. This will open up the man page for stat, which will provide you with more information about this command.
Get file type with file command in Linux
To check file type in Linux, we can use file command. It can be used to check the type of a text file, an image file, or any other type of file. To use this method, you will need to open up a terminal window and change into the directory where the file is located.
Once you are in the correct directory, you will need to type “file” followed by the name of the file that you want to check.
For example, if we wanted to check the type of the file “readme.txt”, we would type “file readme.txt”.
In the example above, we are checking the file type of a text file.
The file command in Linux is used to identify the type of a file. It can also be used to determine whether a file is a binary or text file.
If you want more information about the file command and what it can do, you can type “man file” to open up the man page for this command.
List file type with ls command in Linux
To get the file type in Linux, we can also use ls command with -l option. For example, if we wanted to check the type of the file “readme.txt”, we would type “ls -l readme.txt”.
This command will give you useful information about the file, including the type.
The -l ( lowercase L) option tells ls to print files in a long listing format.
When the long listing format is used, you can see the following file information:
- The file type.
- The file permissions.
- Number of hard links to the file.
- File owner.
- File group. .
- Date and Time.
- File name.
-rw-r—r— 1 root root 337 Oct 4 11:31 readme.txt
Let’s explain the most important columns of the output.
The first character shows the file type. In this example, the first character is -, which indicates a regular file. Values for other file types are as follows:
- – – Regular file.
- b – Block special file.
- c – Character special file.
- d – Directory.
- l – Symbolic link.
- n – Network file.
- p – FIFO.
- s – Socket.
As you can see, a – character indicates that the file is a regular file, while a d character indicates that the file is a directory.
If you want more information about the ls command and what it can do, you can type the following command: man ls
Check file type with find command in Linux
To search for files with a specific file type in Linux, we can use using the find command with -type option.
For example, if we wanted to find all of the files and names with txt in the current directory, we would type
find . -type f -name «*.txt»
This will search through all of the files in the current directory and return any files that have a .txt extension.
You can also use the -type option to find other types of files, such as directories (-type d) or symbolic links (-type l).
There are many other methods that can be used to check file type in Linux. However, these are four of the most common methods. If you are having difficulty identifying a file’s format, these methods should help you out.
Do you have any other tips for checking file type in Linux? Let us know in the comments below! And don’t forget to check out our other Linux tutorials! Thanks for reading! =)