File type command in 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.

Читайте также:  Txt to pdf converter linux

Сравните вывод команды с опцией -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.

Источник

How to Find Out File Types in Linux

In Linux, everything is considered as a file. In UNIX, seven standard file types are regular, directory, symbolic link, FIFO special, block special, character special, and socket. In Linux/UNIX, we have to deal with different file types to manage them efficiently.

In Linux/UNIX, Files are mainly categorized into 3 parts:

The easiest way to find out file type in any operating system is by looking at its extension such as .txt, .sh, .py, etc. If the file doesn’t have an extension then in Linux we can use file utility. In this article, we will demonstrate file command examples to determine a file type in Linux.

To find out file types we can use the file command.

Syntax: file [OPTION…] [FILE…]

You can run the following command to verify the version of the file utility:

We can test a file type by typing the following command:

We can pass a list of files in one file and we can specify using the -f option as shown below:

cat file.txt file -f file.txt

Using the -s option we can read the block or character special file.

Using -b option will not prepend filenames to output lines

Using -F option will use string as separator instead of “:”.

Using -L option will follow symlinks (default if POSIXLY_CORRECT is set):

We can use the –extension option to print a slash-separated list of valid extensions for the file type found.

For more information and usage options, you can use the following command:

We can also use ls command to determine a type of file.

The following table shows the types of files in Linux and what will be output using ls and file command

File Type Command to create the File Located in The file type using “ls -l” is denoted using FILE command output
Regular FIle touch Any directory/Folder PNG Image data, ASCII Text, RAR archive data, etc
Directory File mkdir It is a directory d Directory
Block Files fdisk /dev b Block special
Character Files mknod /dev c Character special
Pipe Files mkfifo /dev p FIFO
Symbol Link Files ln /dev l Symbol link to
Socket Files socket() system call /dev s Socket

Types of File and Explanation

Regular Files

Regular files are ordinary files on a system that contains programs, texts, or data. It is used to store information such as text, or images. These files are located in a directory/folder. Regular files contain all readable files such as text files, Docx files, programming files, etc, Binary files, image files such as JPG, PNG, SVG, etc, compressed files such as ZIP, RAR, etc.

Or we can use the “file *” command to find out the file type

Directory Files

The sole job of directory files is to store the other regular files, directory files, and special files and their related information. This type of file will be denoted in blue color with links greater than or equal to 2. A directory file contains an entry for every file and sub-directory that it houses. If we have 10 files in a directory, we will have 10 entries in the directory file. We can navigate between directories using the cd command

We can find out directory file by using the following command:

We can also use the file * command

Special Files

1. Block Files:

Block files act as a direct interface to block devices hence they are also called block devices. A block device is any device that performs data Input and Output operations in units of blocks. These files are hardware files and most of them are present in /dev.

We can find out block file by using the following command:

We can use the file command also:

2. Character device files:

A character file is a hardware file that reads/writes data in character by character in a file. These files provide a serial stream of input or output and provide direct access to hardware devices. The terminal, serial ports, etc are examples of this type of file.

We can find out character device files by:

We can use the file command to find out the type of file:

3. Pipe Files:

The other name of pipe is a “named” pipe, which is sometimes called a FIFO. FIFO stands for “First In, First Out” and refers to the property that the order of bytes going in is the same coming out. The “name” of a named pipe is actually a file name within the file system. This file sends data from one process to another so that the receiving process reads the data first-in-first-out manner.

We can find out pipe file by using the following command:

We can use the file command to find out file type:

A symbol link file is a type of file in Linux which points to another file or a folder on your device. Symbol link files are also called Symlink and are similar to shortcuts in Windows.

We can find out Symbol link file by using the following command:

We can use the file command to find out file type:

5. Socket Files:

A socket is a special file that is used to pass information between applications and enables the communication between two processes. We can create a socket file using the socket() system call. A socket file is located in /dev of the root folder or you can use the find / -type s command to find socket files.

We can find out Symbol link file by using the following command:

We can use the file command to find out file type:

Источник

How to Find Out File Types in Linux

The easiest way to determine the type of a file on any operating system is usually to look at its extension (for instance .xml, .sh, .c, .tar etc..). What if a file doesn’t have an extension, how can you determine its type?

Linux has a useful utility called file which carry out some tests on a specified file and prints the file type once a test is successful. In this short article, we will explain useful file command examples to determine a file type in Linux.

Note: To have all the options described in this article, you should be running file version 5.25 (available in Ubuntu repositories) or newer. CentOS repositories have an older version of file command (file-5.11) which lacks some options.

You can run following command to verify the version of file utility as shown.

$ file -v file-5.33 magic file from /etc/magic:/usr/share/misc/magic

Linux file Command Examples

1. The simplest file command is as follows where you just provide a file whose type you want to find out.

Find File Type in Linux

2. You can also pass the names of the files to be examined from a file (one per line), which you can specify using the -f flag as shown.

Find Files Type in Filename List

3. To make file work faster you can exclude a test (valid tests include apptype, ascii, encoding, tokens, cdf, compress, elf, soft and tar) from the list of tests made to determine the file type, use the -e flag as shown.

$ file -e ascii -e compress -e elf etc

4. The -s option causes file to also read block or character special files, for example.

$ file -s /dev/sda /dev/sda: DOS/MBR boot sector, extended partition table (last)

5. Adding the -z options instructs file to look inside compressed files.

Determine Compressed Files

6. If you want to report information about the contents only not the compression, of a compressed file, use the -Z flag.

7. You can tell file command to output mime type strings instead of the more traditional human readable ones, using the -i option.

$ file -i -s /dev/sda /dev/sda: application/octet-stream; charset=binary

8. In addition, you can get a slash-separated list of valid extensions for the file type found by adding the –extension switch.

For more information and usage options, consult the file command man page.

That’s all! file command is a useful Linux utility to determine the type of a file without an extension. In this article, we shared some useful file command examples. If you have any questions or thoughts to share, use the feedback form below to reach us.

Источник

Оцените статью
Adblock
detector