Sort and index a BAM file with samtools
Coordinate-sort a BAM file with samtools and build its .bai index so tools can randomly access any genomic region.
Prerequisites
- samtools installed (`samtools sort`, `samtools index`)
- A BAM (or SAM) alignment file
1Sort the BAM by coordinate
Coordinate-sort the alignments and write a fresh BAM. `-@ 4` uses four threads; add `-m 2G` to raise per-thread memory for large files. The command is silent on success.
samtools sort -@ 4 -o sorted.bam input.bamExpected output
# no output on success; sorted.bam is written, coordinate-ordered2Build the index
Index the sorted BAM so tools can jump straight to any region without a full scan. This writes sorted.bam.bai next to it and prints nothing on success.
samtools index sorted.bamExpected output
# no output; creates sorted.bam.bai in the same directory3Confirm the sort order and index
Read the header and check the @HD line: SO:coordinate proves the file is sorted. Confirm the index exists by listing the .bai alongside the BAM.
samtools view -H sorted.bam | grep '@HD'
ls -1 sorted.bam*Expected output
@HD VN:1.6 SO:coordinate
sorted.bam
sorted.bam.baiTroubleshooting
samtools index: the input is not sorted (chromosomes out of order)
You must coordinate-sort before indexing. Run `samtools sort -@ 4 -o sorted.bam input.bam` (step 1) first, then index the sorted output rather than the original file.
A downstream tool wants name-sorted input (e.g. samtools fixmate, htseq-count)
Sort by read name instead of coordinate with `samtools sort -n -@ 4 -o namesorted.bam input.bam`. Name-sorted BAMs group mate pairs together and cannot be indexed with samtools index.