Форматирование в Ext4
В одной из прошлых статей мы говорили про файловую систему Ext4, рассмотрели её историю и опции монтирования. Теперь пришло время поговорить про форматирование раздела в Ext4.
Это довольно просто сделать даже с помощью различных графических инструментов. Но если вы хотите использовать специальные параметры файловой системы, то вам понадобится утилита mkfs. О ней мы сегодня и поговорим.
Форматирование в Ext4
Я предполагаю, что раздел, который вы хотите отформатировать в Ext4 у вас уже есть. Если его ещё нет, обратитесь к статье как пользоваться gparted или как пользоваться parted чтобы его создать.
1. Опции mke2fs
Для форматирования мы будем использовать утилиту mkfs.ext4 или mke2fs. Это одна и та же утилита. У неё такой синтаксис:
$ mkfs.ext4 опции /раздел/диска
Ей можно передавать такие опции:
- -b — размер блока. Доступные значения: 1024, 2048 и 4096;
- -c — проверить устройство на битые сектора перед созданием файловой системы;
- -d — скопировать содержимое указанной папки в корневую папку файловой системы;
- -D — использовать прямые методы чтения и записи с диска чтобы не использовать кэш память;
- -e — поведение файловой системы при ошибке. Доступные значения: continue, remount-ro, panic;
- -E — расширенные опции файловой системы;
- -F — принудительно создать файловую систему, даже если во время создания возникают ошибки или файловая система уже существует и примонтирована;
- -j — использовать журнал файловой системы ext3;
- -l — прочитать список плохих секторов на диске из файла;
- -L — задать метку для раздела с этой файловой системой;
- -m — процент блоков, зарезервированных для суперпользователя, по умолчанию 5%;
- -n — не создавать файловую систему, а только отобразить её информацию, что выводится в процессе создания;
- -O — активировать или деактивировать те или иные возможности файловой системы. Сами возможности мы рассмотрим ниже;
- -q — выводить минимум информации во время выполнения;
- -S — записать только суперблок и описание групп, таблица Inode остаётся неизменной. Это может быть полезно для восстановления повреждённой файловой системы;
- -t — тип файловой системы. Доступно: ext2, ext3, ext4;
- -U — указать UUID для раздела с файловой системой;
- -v — максимально подробный вывод;
- -V — вывести версию утилиты.
2. Возможности Ext4
С помощью опции -O можно включить такие возможности файловой системы:
- 64bit — файловая система сможет занимать место больше чем 2 в 32 степени блоков. При размере блока 4 килобайта, это примерно один терабайт;
- encrypt — включить поддержку шифрования для файловой системы;
- ext_attr — включить расширенные атрибуты;
- has_journal — использовать журнал, по умолчанию включена;
- huge_file — разрешить создавать файлы, размером больше двух терабайт;
- large_dir — увеличивает количество файлов, которые могут находится в одной папке;
- metadata_csum — включает расчёт и проверку контрольных сумм для всех метаданных файловой системы;
- meta_bg — позволяет изменять размер раздела в реальном времени, когда файловая система смонтирована и используется;
- mmp — запрещает монтирование файловой системы к нескольким точкам одновременно;
- quota — включает поддержку квот;
Здесь рассмотрены не все опции файловой системы и её возможности, а только самые интересные. Более подробнее смотрите информацию на man страницах для mkfs.ext4 и ext4.
3. Простое форматирование
А теперь давайте попробуем создать файловую систему ext4 с меткой DATA:
sudo mke2fs -t ext4 -L DATA /dev/sdb1

Здесь и далее /dev/sdb1 — это путь к вашему разделу жесткого диска, который вы хотите отформатировать. Чтобы не резервировать место для суперпользователя укажите значение 0 в опции -m:
sudo mke2fs -t ext4 -L DATA -m 0 /dev/sdb1
Для того чтобы выполнить проверку диска на наличие битых секторов используйте опцию -c или -cc для более долгой но тщательной проверки:
sudo mke2fs -t ext4 -L DATA -c /dev/sdb1
4. Включение проверки контрольных сумм
Теперь поговорим про возможности. Для включения контрольных сумм для всех метаданных используйте возможность metadata_csum:
sudo mke2fs -t ext4 -L DATA -O metadata_csum /dev/sdb1
5. Отключение журналирования
Если вы хотите отключить журналирование в файловой системе используйте значок ^ перед возможностью has_journal:
mke2fs -t ext4 -L DATA -O ^has_journal /dev/sdb1
6. Поддержка квот
Для включения поддержки квот на разделе создание файловой системы ext4 выполняется с опцией quota:
mke2fs -t ext4 -L DATA -O quota /dev/sdb1
Для управления квотами установите пакет quota:
sudo apt install quota
Файловую систему надо примонтировать с поддержкой квот:
sudo mount -o quota /dev/sdb1 /mnt
Затем нужно выполнить такую команду для инициализации файлов квот:
sudo quotacheck -um
Далее можно настроить квоты для нужного пользователя. Например:
sudo edquota sergiy

В открывшемся файле вы можете настроить квоты по блокам и inode для этого пользователя. После этого они будут автоматически применены.
7. Поддержка шифрования
Для создания файловой системы с поддержкой шифрования используйте возможность encrypt:
mke2fs -t ext4 -L DATA -O encrypt /dev/sdb1
Шифрование выполняется на уровне папок. Поэтому сначала давайте примонтируем только что созданную файловую систему, а потом создадим папку /ecrypted:
sudo mount /dev/sdb1 /mnt
sudo mkdir /mnt/ecrypted
Для настройки шифрования надо использовать утилиту fscrypt. В Ubuntu утилита устанавливается так:
sudo apt install fscrypt
Затем выполните первоначальную инициализацию:
sudo fscrypt setup

После этого инициализируйте шифрование для только что созданной файловой системы:
sudo fscrypt setup /mnt

Папка должна принадлежать пользователю, для которого вы будете её шифровать:
sudo chown sergiy:sergiy /mnt/encrypted
Чтобы зашифровать папку выполните:
fscrypt encrypt /mnt/encrypted

Утилита спросит каким образом защищать вашу папку, выберите пункт 2 чтобы ввести свой пароль. Затем введите пароль два раза:
fscrypt status /mnt/encrypted/

Выводы
В этой статье мы рассмотрели как отформатировать в Ext4 раздел диска, а также какие опции можно указать при форматировании. Мы разобрались как отключить журналирование, включить квоты или шифрование на уровне файловой системы.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Reformatting Disk Drive on Linux to ext4: parted command
This walkthrough for reformatting a drive (already formatted) to ext4 on Linux is inspired heavily from the sources found in the reference section. The only difference is some added clarity and detail for the reformatting process
Walkthrough
What follows is a short walkthrough for finding a disk connected to the system, removing a partition, and making a new partition.
Find Device Name
First, physically connect the drive to the system, either through USB (for external drives like on the RPi) or through SATA on the motherboard (i.e. for PCs). Once connected, the device can be found using the lsblk command like so:
The above example output was taken from a Raspberry Pi 2. The device labeled sda is a Seagate 5TB External Hard Drive, whereas the mmclk0 is the micro SD card that is formatted with the Raspibian OS. The important thing here, is we now know which device is our Hard Drive.
If we do a quick ls /dev , we can see ALL devices connected to the system:
Without going into great detail about what all these “devices” are, we can see that in the third column our device sda is located. WARNING: If you have more than one drive connected, the label they are given may change. This means that you cannot count on the drive to always be labeled sda . If there are two drives connected, one will be labeled sda and the other sdb , BUT there is no guarantee which will get which label … it can change between reboots etc … Always check with lsblk or other commands (i.e. sudo fdisk -l ) which drives have been labeled which device files.
Now we can move on to using the parted command.
Parted Command 1
Now that we are clear we have the right drive, fire up an interactive parted session by launching the following (using the device file name we found for our drive earlier):
If we type help we can see the potential reformatting options:
Remove Partition
We can see that rm NUMBER will delete a partition, but how do we know what are the partitions? Simple, we run print like so:
Here we see that we have one partition. To remove it simply type:
Simply repeat this with all partitions you want to remove (i.e. rm 2 , rm 3 ). Now let us look at adding a new partition.
Adding Partition 2
First to add a new partition, we can exit the interactive session and simply call parted and pass the commands to it. We will do this to set the new partition standard (this assumes you have a fresh drive, or have already removed all the partitions before using rm NUMBER ):
Now we can create a new partition spanning the whole disk:
This will create one primary partition with the ext4 format (which parted does not support formatting). Now we are ready to add an ext4 file system to this partition.
Formatting ext4
Finally we only need to run a simple command to complete the reformatting of the drive, with a new partition in the ext4 format:
This will create the ext4 file system on the partition at /dev/sda1 we created earlier. The -L flag will set the label of the partition to whatever you set as OPTIONAL_DISK_NAME . This is optional and not necessary.
Summary
The drive is now completely reformatted with a fresh partition. You can now mount this drive:
A. Partitioning (for >2GB Harddisk) (New) (Updated on 18 Jan 2020)
![]()
2. But we cannot mount it right now, if we mount it now, errors will come out. We need to partition it first, we use parted to partition:
3. Within the parted, type the following to have gpt partition, gpt can allow partition larger than 2GB:
4. Set the size for partition, I here partition from 0GB to 4GB:
5. Then quit the parted:
B. Formatting
- Format the newly partitioned harddisk:
C. Mounting (including auto mount after reboot)
- Usually drive is mounted in /mnt/. Create a new directory in /mnt/ first.
2. Then we can mount it by:
3. But we need to mount it for every time we reboot. To mount it automatically after each reboot, I use nano to modify the file /etc/fstab:
4. Enter following at the end of file:
The first item is the path for the hard drive. The second one is the destination for the mounted drive, where we want to mount. The third one is the format type. The forth to sixth one I just kept as defaults, 0 and 0.
D. Checking whether the hard drive is mounted
To check if the drive sdb, is mounted? Use mount command:
- mount
E. Unmounting (Updated on 05 May 2020)
To unmount, simply using the umount command:
But sometimes, the mounted harddisk maybe still in use which makes you cannot unmount. To unmount under this condition, there is a lazy mode:
F. Partitioning Using fdisk (for <2GB Harddisk) (Old)
- First, after connecting the harddisk to the computer by SATA and power cables, we can check the new 4-TB harddisk by:
2. But we cannot mount it right now, if we mount it now, errors will come out. We need to partition it first:
How to Format Disk Partitions in Linux
A disk partition must be formatted and mounted before use. The formatting process can also be done for several other reasons, such as changing the file system, fixing errors, or deleting all data.
In this tutorial, you will learn how to format and mount disk partitions in Linux using ext4, FAT32, or NTFS file system.

- A system running Linux
- A user account with sudo or root privileges
- Access to a terminal window / command line (Activities > Search > Terminal)
Checking the Partitions
Before formatting, locate a partition you wish to format. To do so, run the lsblk command that displays block devices. Block devices are files that represent devices such as hard drives, RAM disks, USB drives, and CD/ROM drives.
The terminal prints out a list of all block devices as well as information about them:
- NAME – Device names
- MAJ:MIN – Major or minor device numbers
- RM – Whether the device is removable (1 if yes, 0 if no)
- SIZE – The size of the device
- RO – Whether the device is read-only
- TYPE – The type of the device
- MOUNTPOINT – Device’s mount point
We will use the /dev/sdb1 partition as an example.

The lsblk command without additional options does not display information about the devices’ file systems.
To display a list containing file system information, add the -f option:
The terminal prints out the list of all block devices. The partitions that do not contain information on the file system in use are non-formatted partitions.

Note: Consider learning how to create partitions in Linux.
Formatting Disk Partition in Linux
There are three ways to format disk partitions using the mkfs command, depending on the file system type:
- ext4
- FAT32
- NTFS
The general syntax for formatting disk partitions in Linux is:
Formatting Disk Partition with ext4 File System
1. Format a disk partition with the ext4 file system using the following command:
2. Next, verify the file system change using the command:
The terminal prints out a list of block devices.
3. Locate the preferred partition and confirm that it uses the ext4 file system.

Formatting Disk Partition with FAT32 File System
1. To format a disk with a FAT32 file system, use:
2. Again, run the lsblk command to verify the file system change and locate the preferred partition from the list.
The expected output is:

Formatting Disk Partition with NTFS File System
1. Run the mkfs command and specify the NTFS file system to format a disk:
The terminal prints a confirmation message when the formatting process completes.
2. Next, verify the file system change using:
3. Locate the preferred partition and confirm that it uses the NFTS file system.

Mounting the Disk Partition in Linux
Before using the disk, create a mount point and mount the partition to it. A mount point is a directory used to access data stored in disks.
1. Create a mount point by entering:
2. After that, mount the partition by using the following command:
Note: Replace [mountpoint] with the preferred mount point (example: /usr/media ).
There is no output if the process completes successfully.

3. Verify if the partition is mounted using the following command:
The expected output is:

Understanding the Linux File System
Choosing the right file system before formatting a storage disk is crucial. Each type of file system has different file size limitations or different operating system compatibility.
The most commonly used file systems are:
- FAT32
- NTFS
- ext4
Their main features and differences are:
| File System | Supported File Size | Compatibility | Ideal Usage |
| FAT32 | up to 4 GB | Windows, Mac, Linux | For maximum compatibility |
| NTFS | 16 EiB – 1 KB | Windows, Mac (read-only), most Linux distributions | For internal drives and Windows system file |
| Ext4 | 16 GiB – 16 TiB | Windows, Mac, Linux (requires extra drivers to access) | For files larger than 4 GB |
Note: Refer to our Introduction to Linux File System article to learn more about the evolution and features of different Linux file systems.
After following this tutorial, you should be able to format and mount a partition in Linux in various file systems. Partition manipulation is essential for efficient data management, and next, we recommend learning how to delete a partition in Linux.