Check file type linux

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.

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.

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

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.

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.

Читайте также:  Файловые системы windows их основные возможности

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

7 Ways to Determine the File System Type in Linux (Ext2, Ext3 or Ext4)

A file system is the way in which files are named, stored, retrieved as well as updated on a storage disk or partition; the way files are organized on the disk.

A file system is divided in two segments called: User Data and Metadata (file name, time it was created, modified time, it’s size and location in the directory hierarchy etc).

In this guide, we will explain seven ways to identify your Linux file system type such as Ext2, Ext3, Ext4, BtrFS, GlusterFS plus many more.

1. Using df Command

df command reports file system disk space usage, to include the file system type on a particular disk partition, use the -T flag as below:

df Command – Find Filesystem Type

For a comprehensive guide for df command usage go through our articles:

2. Using fsck Command

fsck is used to check and optionally repair Linux file systems, it can also print the file system type on specified disk partitions.

The flag -N disables checking of file system for errors, it just shows what would be done (but all we need is the file system type):

fsck – Print Linux Filesystem Type

3. Using lsblk Command

lsblk displays block devices, when used with the -f option, it prints file system type on partitions as well:

lsblk – Shows Linux Filesystem Type

4. Using mount Command

mount command is used to mount a file system in Linux, it can also be used to mount an ISO image, mount remote Linux filesystem and so much more.

When run without any arguments, it prints info about disk partitions including the file system type as below:

Mount – Show Filesystem Type in Linux

5. Using blkid Command

blkid command is used to find or print block device properties, simply specify the disk partition as an argument like so:

blkid – Find Filesystem Type

6. Using file Command

file command identifies file type, the -s flag enables reading of block or character files and -L enables following of symlinks:

file – Identifies Filesystem Type

7. Using fstab File

The /etc/fstab is a static file system info (such as mount point, file system type, mount options etc) file:

Fstab – Shows Linux Filesystem Type

That’s it! In this guide, we explained seven ways to identify your Linux file system type. Do you know of any method not mentioned here? Share it with us in the comments.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Windows chm файл не открывается

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to Determine the File Type of a File Using Linux

Find the file type of any file or group of files with the ‘file’ command

Most people look at the extension of a file and then guess the type of file from that extension. For example, when you see a file with an extension of gif, jpg, bmp, or png you think of an image file, and when you see a file with an extension of zip, you assume the file has been compressed using a zip compression utility.

A file can use one extension but be something altogether different. Linux doesn’t use file extensions; rather, the file’s type is part of the file name. To find out the true file type use the file command.

How the ‘file’ Command Works

The file command runs three sets of tests against a file:

  • Filesystem tests
  • Magic tests
  • Language tests

The first set of tests to return a valid response prompts the file type to be printed.

Filesystem tests examine the return from a stat system call. The program checks to see if the file is empty and whether it is a special file. If the file type is found in the system header file, it is returned as the valid file type.

The magic tests check the contents of a file and specifically a few bytes at the beginning that help to determine the file type. Various files are used to help match up a file with its file type, and these are stored in:

  • /etc/magic
  • /usr/share/misc/magic.mgc
  • /usr/share/misc/magic

Override these files by placing a file in your home folder called $HOME/.magic.mgc or $HOME/.magic.

The final tests are language tests. The file is checked to see if it is a text file. By testing the first few bytes of a file, the test deduces whether the file is an ASCII, UTF-8, UTF-16, or another format that identifies the file as a text file. When the character set is deduced, the file is tested against different languages.

How to Use the ‘file’ Command

The file command takes the following form:

The output will be something like this:

  • /etc/passwd: ASCII text
  • /etc/pam.conf: ASCII text
  • /etc/opt: directory

Standard wildcards work, too. For example, to test all files in the present working directory, use:

To test for directories that start with the letter D (case sensitive) try this:

The results could be Desktop, Documents, and Downloads, for example.

Compressed Files

When you run the file command against a compressed file you see output something like this:

  • file.zip: ZIP archive data, at least V2.0 to extract

While this result tells you that the file is an archive file, you don’t know the contents of the file. Look inside the zip file to see the file types of the files within the compressed file. The following command runs the file command against the files inside a ZIP file:

file -z filename

The output now shows the file types of files in the archive.

Источник

Как определить тип файла файла с помощью Linux

Найдите тип файла любого файла или группы файлов с помощью команды FILE

Большинство людей смотрят на расширение файла, а затем угадывают тип файла с этим расширением. Например, когда вы видите файл с расширением gif, jpg, bmp или png, вы думаете о файле изображения, а когда вы видите файл с расширением zip, вы предполагаете, что файл был сжат с помощью утилиты сжатия zip ,

Читайте также:  Что будет если закончится лицензия windows 10

В действительности, файл может иметь одно расширение, но быть чем-то совершенно другим. В Linux вы узнаете истинный тип файла с помощью команды file .

Как работает команда File

Команда file выполняет три набора тестов для файла:

  • Тесты файловой системы
  • Магические тесты
  • Языковые тесты

Первый набор тестов для возврата правильного ответа приводит к печати типа файла.

Тесты файловой системы проверяют отдачу от системного вызова stat. Программа проверяет, является ли файл пустым и является ли он специальным файлом. Если тип файла найден в системном заголовочном файле, он возвращается как допустимый тип файла.

Магические тесты проверяют содержимое файла и, в частности, несколько байтов в начале, которые помогают определить тип файла. Различные файлы используются, чтобы помочь сопоставить файл с его типом файла, и они хранятся в:

Переопределите эти файлы, поместив файл в вашу домашнюю папку с именем $ HOME/.magic.mgc или $ HOME/.magic.

Финальные тесты – языковые тесты. Файл проверяется, чтобы увидеть, является ли он текстовым файлом. Тестируя первые несколько байтов файла, тест может определить, является ли файл ASCII, UTF-8, UTF-16 или другим форматом, который идентифицирует файл как текстовый файл. Когда выводится набор символов, файл проверяется на разных языках.

Если ни один из тестов не работает, выводом являются данные.

Как использовать команду «Файл»

Команда file может быть использована следующим образом:

Например, представьте, что у вас есть файл с именем file1, и вы запускаете следующую команду:

Вывод примерно такой:

Выходные данные определяют, что file1 – это файл изображения или, точнее, файл переносимой сетевой графики (PNG).

Различные типы файлов дают разные результаты:

  • Тип файла ODS : электронная таблица OpenDocument
  • Тип файла PDF : документ PDF, версия 1.4
  • Тип файла CSV : текст ASCII, с очень длинными строками, с индикаторами строк CRLF

Настройте вывод из команды File

По умолчанию команда file предоставляет имя файла и все детали над файлом. Если вы хотите, чтобы только детали без имени файла повторялись, используйте следующий переключатель:

Вывод примерно такой:

Вы также можете изменить разделитель между именем файла и типом. По умолчанию в качестве разделителя используется двоеточие, но вы можете изменить его на что угодно, например на символ канала, следующим образом:

Вывод примерно такой:

Обработка нескольких файлов

По умолчанию вы используете команду file для одного файла. Однако вы можете указать имя файла, которое содержит список файлов, которые будут обработаны командой file.

Например, откройте файл с именем testfiles с помощью редактора nano и добавьте в него следующие строки:

Сохраните файл и выполните следующую команду:

Результат будет примерно таким:

  • /etc/passwd: текст ASCII
  • /etc/pam.conf: текст ASCII
  • /etc/opt: каталог

Сжатые файлы

По умолчанию, когда вы запускаете команду file для сжатого файла, вы видите что-то вроде этого:

Хотя это говорит о том, что файл является архивом, вы не знаете его содержимого. Вы можете заглянуть внутрь zip-файла, чтобы увидеть типы файлов в сжатом файле. Следующая команда запускает команду file для файлов внутри ZIP-файла:

Вывод теперь показывает типы файлов файлов в архиве.

Большинство людей используют команду file, чтобы найти основной тип файла.Чтобы узнать больше о возможностях, которые предлагает команда file, введите в окне терминала следующее:

Эта команда открывает документацию по программному обеспечению Linux, включенную в систему.

Источник

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