Sort a BAM file by coordinate

bam samtools · raw · bash

Sort a BAM file by chromosome and position, keeping the index and read names
out of the way. Always write to a new file: samtools sort refuses to
overwrite its input.

samtools sort -@ 2 -o sorted.bam in.bam
samtools index sorted.bam
samtools quickcheck -v sorted.bam

For long reads the memory footprint grows with the number of reads in flight,
so -@ buys speed but not memory. When the machine is small, drop it:

samtools sort -o sorted.bam in.bam

samtools quickcheck -v prints nothing when the file is intact, which makes it
easy to use in a pipeline with set -e.