Or how you don’t need to defrag your Linux drive. Windows users have a habit to defragment their drives once in a while, to speed things up. That was a good idea until newer versions of Windows that have a schedule for auto defrag once a week or so. Defragmenting a Windows drive was necessary due to how files were allocated on the hard disk.
Microsoft’s old FAT file system doesn’t attempt to arrange files intelligently so when you create a file, it’s saved as close to the start of the disk as possible and when you create a second file, it’s saved right next to the first one. But when the first file is edited and grows in size, the new portion of the file is saved wherever there’s room on the disk and basically it becomes scattered all over the drive. So when you open the file, the hard disk’s heads must skip all over the drive between different physical locations to read all chunks of the same file.
NTFS, the newer Microsoft file system tries to do things differently by allocating a buffer (free space) around the files but in case of files that grow very much in size, the fragmentation will occur once again.
However, solid state drives (SSD) don’t have any moving parts and the deframenting will be pointless, in fact, defragmenting a SSD will actually reduce its life.
As for Linux file systems (ext2, ext3 and ext4), it allocates files more intelligently. Instead of placing files right next to each other, it scatters them all over the drive, leaving large chunks of free space between them. So when a file grows in size, it will most likely have the space to grow into. However, if fragmentation does occur, the Linux file system will attempt to move files around automatically so no defrag tool is needed. Fragmentation on a Linux drive will also occur when you run out of free space so instead of looking for how to defrag a Linux drive, just buy a bigger one ;-)
If, just out of curiosity, you want to know the fragmentation level of your drive, here’s how:
Method 1 – faster
Open a terminal and type:
mount | grep "on / type"
You should see something like this:
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
Now, if you see ext4, run:
Don’t worry if the drive is mounted, the -n option doesn’t touch it, just reads it. However, because the drive is mounted, it will print out some errors but that’s normal.
sudo fsck.ext4 -fn /dev/sda1
For ext3, run:
sudo fsck.ext3 -fn /dev/sda1
This is what you need to look for:
/dev/sda1: 557479/14270464 files (0.4% non-contiguous), 21787429/57072384 blocks
Method 2 – Slower
There’s another way, by using this script:
Select the code, copy it to clipboard and type:
Now press Shift + Insert, Ctrl + X , Y, Enter
Run it with:
chmod +x fragtest
sudo ./fragtest /
This will take a few minutes but the result will be something like this:
0.479340273881245% non contiguous files, 0.965788891489546 average fragments.