How To Defragment a Hard Drive in Ubuntu
We teach you how to defragment a hard drive in Ubuntu easily
Step 1: Defrag Hard Drive using e4defrag
This utility is part of the Linux operating systems and is part of the e2fsprogs suite of tools, but if it is not available, we can execute the following for its installation:
sudo apt-get install e2fsprogs
Once installed we can see the use of e4defrag running the following line:
sudo e4defrag
We can list the partitions of our team by executing the following:
sudo fdisk -l
Now, with this tool we have the option to defragment only one or more files using the following syntax:
sudo e4defrag “path_to_analyze”

But we can also, perhaps being the most crucial issue, the defragmentation of our disk drive. For this we have these options:
Defragment the Unit without Unmount
itIf we do not want to carry out the process of dismantling the unit, we can execute the following line:
sudo e4defrag /
Defragment by Unmount the Units
The next option is to disassemble the units for a more detailed analysis of them. To dismantle the units and carry out the process, we will execute the following:
sudo e4defrag /dev/*
Step 2: Defrag Hard Drive using FSCK
It is advisable to make use of this command from a live CD with the units removed since doing it directly we can affect the data stored there.
For your use, we can execute the following:
fsck -fn /dev/sda1
There we can replace /dev/sda1 with the desired route. As an option we can run fsck in safe mode without affecting the files using the -n parameter, for example, in an ext4 file system we execute the following:
sudo fsck.ext4 -fn /path partition
With these methods it will be possible to defragment the hard disks in Linux environments and thus optimize their use.