Linux show filesystem type

Linux how to determine the file system type

All files accessible in a Linux system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices and they can be remote or local file system. Linux supports numerous file system types. For example it supports Ext2,. Ext3, NFS, FA16, FAT32, NTFS,Sysfs, Procfs etc. To determine the file system type or to find out what type of file systems currently mounted you need to use command called mount or df. Type df command as follows:
$ df -T Output:

df command report filesystem disk space usage and if you pass -T option it will report filesystem type. As you see second command displays file system type (ext3). Type, mount command as follows at shell prompt:
$ mount Output:

As you can see, second last column displays the file system type. For example first line [/dev/hdb1 on / type ext3 (rw,errors=remount-ro)] can be interpreted as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

  • /dev/hdb1 : Partition
  • / : File system
  • ext3 : File system type
  • (rw,errors=remount-ro) : Mount options

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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:

Читайте также:  Windows 10 починили как могли

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.

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.

Источник

10 basic & powerful commands to check file system type in Linux/Unix

Table of Contents

Any operating system must be able to access and manage files on storage devices; however, the manner in which the files are organized on a storage device is actually set by the underlying filesystem.With Linux and Unix there are various filesystem types, so in this article I will share multiple commands and methods to check file system type in Linux and Unix.

Before we try to determine and check file system type, we must be familiar with the term «File System».

What is a FileSystem?

As you probably know, or at least can guess, hard drives are not monolithic entities with data simply spread haphazardly around the hard drive. Hard drives are organized into sectors and clusters. Data of any type is organized into files. Whether it is a document, image, spreadsheet, or even an executable program, it is a file. That file may be stored in one or more clusters.

Filesystems are responsible to organize, find, and work with those files that are on the hard drive. There are issues that any filesystem must address in order to handle files effectively.

The first issue occurs because many files are larger than a single sector or cluster. So, locating the entirety of a file on a hard drive is an issue that must be addressed. The operating system may need to check several clusters, not necessarily contiguous, to find a file.

Another problem is how to store the files in clusters and sectors. Also, a filesystem must address how to handle space left due to deleted or moved files.

Now since we know what is a File System, Let us start with the actual agenda of this article.

Commands to check file system type in Linux or Unix

1. blkid

blkid can determine the type of content (e.g. filesystem or swap) that a block device holds, and also the attributes (tokens, NAME=value pairs) from the content metadata (e.g. LABEL or UUID fields).

You must execute blkid as root user without any directives and check » TYPE » field to check file system type of respective partition or device in Linux or Unix.

With -t, —match-token NAME=value , you can search for block devices with tokens named NAME that have the value value, and display any devices which are found. Common values for NAME include TYPE , LABEL , and UUID

For example to list and check file system type for ext4 FS:

2. lsblk

lsblk lists information about all available or the specified block devices. lsblk command provides more information, better control on output formatting, easy to use in scripts and it does not require root permissions to get actual information.

df is another popular and most used command to display the amount of disk space available on the file system containing each file name argument. If no file name is given, the space available on all currently mounted file systems is shown.

Using -T directive with df command you can print file system type of all the mounted file systems.

Alternatively you can specify a device with df command to check file system type of the respective device

4. findmnt

findmnt will list all mounted filesystems or search for a filesystem. The findmnt command is able to search in /etc/fstab , /etc/mtab or /proc/self/mountinfo . If device or mountpoint is not given, all filesystems are shown.

Using —fstab directive, findmnt command will search in /etc/fstab and with -t it will limit the set of printed filesystems

If used without any directive, findmnt command will give you long list of output with all bind mounts

5. file

file command is normally only attempts to read and determine the type of argument files. Specifying the -s option causes file to also read argument files which are block or character special files. This is useful for determining and to check file system types of the data in raw disk partitions, which are block special files

Читайте также:  Сброс пин кода windows 10 через флешку

6. udevadm

udevadm command queries the udev database for device information stored in the udev database. It can also query the properties of a device from its sysfs representation to help creating udev rules that match this device.

Using —query you can query the database for the specified type of device data. The below command gives a long output so we will grep the required data to check file system type for our device /dev/sda1

Some more commands and methods to determine filesystem type in Linux or Unix

Now above were some of the most used commands to check file system type but there are many other methods using which you can determine filesystem type

7. File /etc/fstab content

Normally all the devices we use are mounted via /etc/fstab file to make the mounting reboot persistent. So you can always refer /etc/fstab file to check file system type, for example:

Here the first column of the file specifies the partition device path while the third column shows the file system type of the respective device.

8. File /etc/mtab content

Similar to /etc/fstab you can also refer /etc/mtab to get the list of currently mounted file system along with the file system type.

Here also the first column of the file specifies the partition device path while the third column shows the file system type of the respective device.

9. File /proc/mounts

Now /proc/mounts file refers /etc/mtab so this is not a new method but just another file which you can look into to check file system type in Linux or Unix.

10. mount command

Again, mount command will also refer /etc/mtab file to get the list of mounted file systems and can also help you determine file system type of individual devices.

Lastly I hope the methods and commands from the article to determine and check file system type on Linux and Unix was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Работа с файловой системой Linux

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

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

В этой статье мы рассмотрим как выполняется работа с файловой системой Linux в терминале. За основу возьмем семейство файловых систем ext2/3/4, так как они самые распространенные среди большого многообразия дистрибутивов Linux.

Основные команды

Для управления файловой системой ext в Linux используется целый набор команд из пакета e2progs. Сюда входят как команды для управления флагами файлов, создания и изменения файловых систем, так и утилиты для отладки файловой системы.

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

  • badblocks — если у вас старый жесткий диск и на нем накопилось много битых блоков, вы можете с помощью этой утилиты пометить их все на уровне файловой системы, чтобы больше не использовать.
  • e2label — позволяет изменить метку раздела с файловой системой ext.
  • fsck — проверка файловой системы linux и исправление найденных ошибок
  • mkfs — позволяет создать файловую систему Linux.
  • resize2fs — изменить размер раздела с файловой системой
  • tune2fs — позволяет изменить файловую систему Linux, настроить ее параметры.

А теперь будет рассмотрена работа с файловой системой linux на примерах.

Работа с файловой системой в Linux

Перед тем как переходить к работе с реальным жестким диском важно попрактиковаться. Если сменить метку или проверить на битые сектора можно и рабочий диск, то создавать новую файловую систему, изменять ее размер, рискуя потерять данные на реальном диске не рекомендуется. Можно отделить небольшой раздел диска для экспериментов с помощью Gparted и выполнять все действия в нем. Допустим, у нас этот раздел будет называться /dev/sda6.

Создание файловой системы

Создать файловую систему linux, семейства ext, на устройстве можно с помощью команды mkfs. Ее синтаксис выглядит следующим образом:

sudo mkfs -t тип устройство

Доступны дополнительные параметры:

  • — проверить устройство на наличие битых секторов
  • -b — размер блока файловой системы
  • -j — использовать журналирование для ext3
  • -L — задать метку раздела
  • -v — показать подробную информацию о процессе работы
  • -V — версия программы

Создаем файловую систему на нашем устройстве. Будем создавать ext3:

Читайте также:  Этот компьютер users user appdata roaming microsoft windows start menu

sudo mkfs -t ext4 -L root /dev/sda6

Creating filesystem with 7847168 4k blocks and 1962240 inodes
Filesystem UUID: 3ba3f7f5-1fb2-47af-b22c-fa4ca227744a
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000
Allocating group tables: done
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

Изменение метки файловой системы

Утилита e2label позволяет изменить или посмотреть метку раздела диска. Принимает всего два параметра — устройство и новую метку если нужно.

sudo e2label /dev/sda6

sudo e2label /dev/sda6 root1

Настройка файловой системы linux

Различные параметры файловой системы, такие как размер блока данных, иноды или зарезервированное место под данные пользователя root можно настроить. Для этого существует утилита tune2fs.

Синтаксис команды очень прост:

$ tune2fs опции устройство

Поддерживаются следующие опции:

  • -j — создать файл журнала. Позволяет превратить файловую систему ext2 в ext3.
  • -J — настроить параметры журнала
  • -l — получить содержимое суперблока
  • -L — изменить метку раздела
  • -m — изменить процент дискового пространства, зарезервированного для суперпользователя
  • -M — изменить последнюю папку монтирования
  • -U — задать UUID файловой системы
  • -C — изменить значение счетчика монтирования
  • -T — изменить последнюю дату проверки файловой системы
  • — изменить периодичность проверок файловой системы с помощью fsck
  • -O — изменить опции файловой системы.

Изменить размер зарезервированного места для суперпользователя до пяти процентов:

sudo tune2fs -m 5 /dev/sda6

Setting reserved blocks percentage to 5% (392358 blocks)

Посмотреть информацию из суперблока, эта команда показывает всю доступную информацию параметрах файловой системы:

Filesystem volume name: root
Last mounted on: /
Filesystem UUID: 3ba3f7f5-1fb2-47af-b22c-fa4ca227744a
Filesystem magic number: 0xEF53
Filesystem revision #: 1 (dynamic)
Filesystem features: has_journal ext_attr resize_inode dir_index filetype extent flex_bg spar
se_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags: signed_directory_hash
Default mount options: user_xattr acl
Filesystem state: clean
Errors behavior: Continue
Filesystem OS type: Linux

Изменить счетчик количества монитрований:

tune2fs -C 0 /dev/sda6

Setting current mount count to 0

Думаю тут смысл понятен, нужно только немного со всем этим поэкспериментировать.

С помощью опции -O мы вообще можем превратить нашу ext3 в ext4 следующей командой:

sudo tune2fs -O extents,uninit_bg,dir_index

После этого действия нужно выполнить проверку файловой системы на ошибки в fsck. Подробнее об этом поговорим ниже.

sudo fsck -np /dev/sda6

Таким образом вы можете изменить файловую систему linux, и настроить по своему усмотрению любые ее параметры.

Изменение размера файловой системы Linux

Раньше такая функция поддерживалась в утилите parted, но потом ее убрали и для этого действия приходится использовать утилиту из набора e2fsprogs — resize2fs.

Запустить утилиту очень просто. Ей нужно передать всего два параметра:

$ resize2fs [опции] устройство размер

Доступны также опции:

  • -M уменьшить файловую систему до минимального размера
  • -f — принудительное изменение, не смотря на потерю данных
  • -F — очистить буфер файловой системы

Размер передается, как и во многих других утилитах, целым числом с указанием единиц измерения, например, 100М или 1G.

Для примера уменьшим размер нашего раздела до 400 Мегабайт:

sudo resize2fs /dev/sda6 400M

Resizing the filesystem on /dev/sda7 to 102400 (4k) blocks.
The filesystem on /dev/sda7 is now 102400 blocks long

Проверка файловой системы Linux

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

$ fsck [опции] устройство

  • -p — автоматическое восстановление
  • -n — только проверка, без восстановления
  • -y — ответить да на все запросы программы
  • — проверить на битые сектора (аналог badblocks
  • -f — принудительная проверка, даже если раздел помечен как чистый
  • -j — внешний журнал файловой системы

Проверка файловой системы Linux выполняется такой командой, проверим диск /dev/sda6, заметьте, что диск должен быть не примонтирован:

sudo fsck -a /dev/sda6

root: clean, 11/32704 files, 37901/102400 blocks

Дефрагментация файловой системы

Хотя и фрагментация нехарактерное явление для файловых систем семейства ext, при очень интенсивном использовании может накапливаться фрагментированость, что будет замедлять работу файловой системы. Для дефрагментации можно использовать стандартную утилиту e4defrag. Просто выполните:

Чтобы проверить нужна ли дефрагментация в Linux выполните эту же команду с опцией -c:

Total/best extents 26247/24953
Average size per extent 1432 KB
Fragmentation score 0
[0-30 no problem: 31-55 a little bit fragmented: 56- needs defrag]
This device (/dev/sda6) does not need defragmentation.
Done.

В поле Fragmentation score отображен процент фрагментации, как видите, у меня 0, нормой считается до 30, 31-55 небольшие проблемы, и больше 56 — нужна дефрагментация.

Выводы

В одной из предыдущих статей мы рассмотрели как выполняется разметка диска с помощью parted. Из этой статьи вы узнали все что нужно о работе с файловой системой. Теперь у вас не возникнет проблем если у вас вдруг не будет доступа к графическим утилитам и нужно будет исправлять ошибки или настраивать файловую систему. Если остались вопросы, спрашивайте в комментариях!

Источник

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