In linux, how do you check if a disk is fragmented?

You can safely run fsck.ext2 on an ext2 ext3 or ext4 filesystem even if it's mounted like this

sudo fsck.ext2 -fn /dev/sdXY

If the drive is mounted, it will output a lot of errors, but the -n argument tells it not to touch the drive.

$ sudo fsck.ext2 -fn /dev/sda1
e2fsck 1.42 (29-Nov-2011)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Ubuntu_Rescue: 291595/1222992 files (0.2% non-contiguous), 1927790/4882432 blocks

The modern ext family of filesystems take balancing and contiguity into consideration when allocating files. In ext3 and ext4 balancing is generally taken care of by applying journal entries in order, and in ext4 specifically, by pre-allocating file-system extents to increase contiguous blocks. Chasing fragmentation levels lower than 20% might not be worth your time, especially if your system is accessing a few files repeatedly. I suggest pursuing these tactics for increasing read speed for a single disk system:

  • increase ram: this increases filesystem cache

  • increase block size: by moving from 1k towards 4k block sizes, you get better performance on reads for files near or larger than your block size

  • if you are pedantic, you can organize large files and small files into partitions by their block size, you might only want to do this if you stored photos, videos and source code in separate directories

  • increase your read-ahead setting using hdparm and/or laptop-mode utility

  • backup and restore your filesystem in a linear fashion such as with tar

If you have multiple disks and are using raid striping and/or LVM, you other factors to consider, such as stripe size.