What is the best way to defragment a FAT filesystem when running Linux/Unix (on usb stick for instance)?
You can check whether a file is fragmented or not using the
That way you could filter out the files that aren't fragmented, and do the copy/copy back only for already fragmented files. That should save you some time. However be aware that there is no guarantee the new file layout will be better than the old one.
The best way is to ignore file fragmentation altogether. Especially on a USB stick it hardly matters, only wastes write cycles, and unlike HDDs, there are no movable parts and thus not much of a penalty due to fragmentation.
Defragmentation should only be necessary if something funny happened that caused files to fragment in a very extreme way. For example torrent clients that download file contents in random order without preallocating. But unless FAT started supporting sparse files at some point that's not even an issue there, as preallocating is mandatory on such a FS.
Let's look at this from a different angle, because you gave an example "on usb stick for instance"
A USB stick is FLASH memory, and there are two things to consider: 1) Since FLASH memory does not have moving parts, there is no noticeable performance gain to be seen by doing a defrag. Defrgs are either for cleaning up the file system or re-org of the file blocks to put them closer to each other - to reduce the physical movements of the arm (seek) and the wait time of the disc spinning (latency). Flash does not have this. 2) Writing and writing and writing on flash memory wears it down. Now, for 100K write endurance maybe your USB stick would last several to 10 years, but the number of time you can write is a "finite" number. Constant defrags to the USB stick eat away at that life because of the endurance limitation.
And this is not just your USB stick, SD cards, Compact FLASH and even SSD drives.
My point, don't defrag just for the hell of it, Know what the underlying technology under the file system is and the implications, and even if it is magnetic and not electronic, too much defrag may eventually corrupt your file system and you loose your files.