Methods of payment Abuse

Disk defragmentation in Linux

23.10.2022, 02:33

Every Windows user is familiar with the fact that there is a disk defragmentation. It is necessary for the hard disk to function quickly, and it is necessary to defragment the disk on which the OS is installed. The Ext4 file system in Linux is not prone to fragmentation. But in practice, it is known that in case of prolonged work on the system, some fragmentation accumulates. Next, we will tell you in detail how to properly perform disk defragmentation in Linux. For this purpose, we will consider the example of the Ext4 file system.

Defragmentation - what is it? In simple words about complicated things

What is fragmentation? Let's look at the theory: a hard disk consists of a large number of small sectors, each one storing a small piece of data. Large files are divided into several smaller fragments.

But Ext4 doesn't fragment like other file systems because it allocates uses space after the written file. And even if fragmentation occurs, it tries to move the file into the free space. Fragmentation occurs when the file system is full, but this is rarely the case.

SSD disks don't need defragmentation. There are no moving parts.

When a user writes a file in a FAT or NTFS system, a certain amount of resources are allocated for this operation, then the next files are written. If it is necessary to update the file and add information to it, other sectors in another part of the disk will be used.

When there are a large number of such files, the file may be distributed across the entire disk, which means that in the case of such an operation as reading, it will have to move the read head, and this will slow down performance. This is what fragmentation is all about.

How defragmentation works in Linux

Use the fsck utility to assess how fragmented the disk is. Pass the -f option. Use the -n option to prevent major changes to the file system:

$ sudo fsck -fn /dev/sdb1

Disk defragmentation in Linux

/dev/sdb1 is the verification partition. Do not perform the check on a mounted system, you will encounter false errors, if no actions are performed on the file system, there will be no damage. The e4defrag utility will help you perform defragmentation, it is located in the e2fsprogs folder.

If you don't have this set of utilities installed yet, install it with the command:

$ sudo apt install e2fsprogs

Next, defragmentation of the desired partition is available. The same /dev/sdb1. Let's mount the partition before defragmentation:

$ sudo mount /dev/sdb1 /mnt

Disk defragmentation in Linux

Then Ext4 defragmentation:

$ sudo e4defrag /dev/sdb1

Disk defragmentation in Linux

Next, you can check the fragmentation again. Unmount the partition before this. Fragmentation 0%:

$ sudo fsck -fn /dev/sdb1

That's it. Don't waste your time just defragmenting SSD disks. They don't need it.