Can NTFS partitions be defragmented on Linux?

Q I have a external hard-drive, NTFS-formatted. I need to defragment it but I don't want to lose the data on it. Can you defragment NTFS on Linux? I run Ubuntu Feisty Fawn on an old PC2800 computer.

A The short answer is no, not really. Why is the drive using NTFS in the first place? If it contains a Windows bootable installation, any attempt you make to defragment it in Linux will most likely render it unbootable in Windows. But if is does contain Windows, why not use that to defragment the drive - Windows can be useful for more than playing games. If the drive is used purely for data, then you can severely reduce fragmentation by copying all the data off, reformatting the drive and copying the data back. This requires an NTFS filesystem with full write support, either the commercial Paragon NTFS for Linux application or NTFS-3G, which is included in the Ubuntu repositories. You'll also need the ntfsprogs package, so fire up Synaptics and install both of those. Now you can do the whole job by opening a terminal, changing to a directory with enough space to hold the contents of the NTFS drive and running

tar cf ntfs.tar /mnt/ntfs && umount /mnt/ntfs && mkntfs /dev/sda1 && mount /dev/sda1
/mnt/ntfs -t ntfs-3g && tar xf ntfs.tar -C /mnt/ntfs

This is all on one line. The two tar commands and mkntfs take a while, so chaining the commands together like this means you don't need to babysit the machine, yet each command will only be executed if the previous one was successful (you don't want to reformat the drive if copying the data failed). This example assumes your drive is at /dev/sda1 and mounted on /mnt/ntfs. Make sure you change these to the correct paths suitable for your machine before you run it. If you are short of space to save the contents, you can create a compressed archive, but this will take longer, particularly when copying for the drive. Do this with

tar czf ntfs.tar.gz /mnt/ntfs && umount /mnt/ntfs && mkntfs /dev/sda1 && mount /dev/sda1

/mnt/ ntfs -t ntfs-3g && tar xf ntfs.tar.gz -C /mnt/ntfs

If you are using NTFS so the drive is readable in Windows (why else would you use it?) and you will only use it with your own Windows computers, a better solution would be to format the disk as ext2 and install the ext2 driver from on your Windows computer(s). Then you no longer have to worry about disk fragmentation and you will get better disk performance in Linux. The above commands will do this is you replace mkntfs with mke2fs and remove

-t ntfs-3g

from the mount command.

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar