Before you start
- You've done Read Alignment with BWA-MEM, so you have a BAM file to work on.
- Comfortable running a few command-line lines. A free Google account to run the notebook.
- Any term new? The Glossary has it.
Learning objectives
By the end of this lesson you will be able to: use the core samtools commands to look inside a BAM, sort reads into genome order, index the sorted BAM, summarize and pull a region, and check how deep the coverage is at a position.
Why a raw BAM isn't ready yet
When BWA finishes, the reads in your BAM file are in the order they came off the sequencer, which is essentially random. To analyze a genome you need to ask questions like "show me every read covering position 1,500 on chr1." Answering that on an unsorted file means scanning the whole thing every time. The fix is two quick steps: sort the reads into genome order, then build an index so any region can be found instantly. Almost every genomics tool expects a sorted, indexed BAM, so this is the universal next step after alignment.
Decode the jargonsamtools
samtools is the standard toolkit for working with SAM, BAM, and CRAM alignment files. It does conversions (SAM to BAM), sorting, indexing, filtering, statistics, and more. You call it as samtools <subcommand>, like samtools sort or samtools view.
โถ Run it in Google Colab
Colab is a free Linux machine in your browser, so samtools runs with nothing to install on your computer.
The five commands you'll actually use
| Command | What it does |
|---|---|
samtools view | Look inside a BAM, convert SAM to BAM, or filter reads. |
samtools sort | Reorder reads by their genome position. |
samtools index | Build the companion .bai index for fast region lookups. |
samtools flagstat | One-glance summary: total, mapped, duplicate, paired reads. |
samtools depth | Report how many reads cover each position (coverage). |
1Look inside the BAM
BAM is binary, so you cannot just cat it. samtools view turns it back into readable text. Add -H to see just the header.
!samtools view -H aligned.bam # the header !samtools view aligned.bam | head -3 # first 3 alignments
2Sort into genome order
This is the key step. samtools sort reorders the reads so they run from the start of each chromosome to the end. We write the result to a new file.
!samtools sort aligned.bam -o aligned.sorted.bam
Decode the jargonCoordinate-sorted
A coordinate-sorted BAM has its reads ordered by chromosome and then by position along that chromosome. It's the order that lets tools (and the index) jump straight to any region instead of reading the whole file. When a tool complains it "expects a sorted BAM," this is what it means.
3Index the sorted BAM
Indexing creates a small companion file (aligned.sorted.bam.bai) that acts like a table of contents. With it, a tool can leap directly to "chr1:1500" without scanning everything before it. You must sort first; you cannot index an unsorted BAM.
!samtools index aligned.sorted.bam !ls -lh aligned.sorted.bam*
4Summarize and pull a region
With a sorted, indexed BAM you get two superpowers. flagstat gives you the health summary, and view with a region string instantly returns just the reads over that spot.
!samtools flagstat aligned.sorted.bam # Pull only the reads covering positions 1000-1100 on chr1: !samtools view aligned.sorted.bam chr1:1000-1100 | wc -l
That region query is the payoff of indexing. On a real, multi-gigabyte BAM it typically returns in well under a second instead of minutes.
โ ๏ธ Sort before you index
Indexing only works on a coordinate-sorted BAM. If you try to index the raw output of the aligner, samtools will refuse. The reliable habit is always the same order: align, sort, index.
5How deep is the coverage?
Coverage (or depth) is how many reads overlap a given position. It's one of the most important quality numbers in genomics: variant callers trust a position more when many reads agree on it.
!samtools depth aligned.sorted.bam | head # average depth across ALL positions (-a includes positions with zero reads): !samtools depth -a aligned.sorted.bam | awk '{sum+=$3} END {print "mean depth:", sum/NR}' # or let samtools summarise coverage per chromosome: !samtools coverage aligned.sorted.bam
Decode the jargonCoverage / depth
Coverage (often written like "30x") is the average number of reads stacked over each base, averaged over all positions, including any with no reads (that is why the command above uses -a; without it, empty positions are skipped and the average looks better than it is). Higher coverage means more evidence at every position, so you can call variants with more confidence. Too little coverage and you can't tell a real variant from a sequencing error.
Where this leads
A sorted, indexed BAM with known coverage is exactly what a variant caller wants. In the next and final Track 2 lesson, you'll feed this file to a variant caller and produce a VCF, the list of every place your sample differs from the reference. That's the capstone that ties the whole workflow together.
๐ถ Level up: mark duplicates
Real pipelines add one more step before variant calling: marking PCR duplicates (identical reads created during library prep, which can bias variant calls). Tools like samtools markdup or Picard's MarkDuplicates flag them so callers can ignore them (for paired-end data, run samtools fixmate -m on name-sorted reads first, as the variant-calling lesson shows). The principle is the same survival-kit thinking: clean the BAM before you trust it.
Try it here: work with a real BAM in your browser
The practice data is simulated: a 10,000-base chromosome called chr1 and 1,780 reads of 100 bases, built so the results are small, fast and checkable. Press Run on each box; a real Linux terminal opens at the bottom of the page. No install, no account. aligned.bam from the alignment lesson is ready. Type the commands without the Colab !.
samtools view -H aligned.bam samtools view aligned.bam | head -3
samtools sort aligned.bam -o aligned.sorted.bam samtools index aligned.sorted.bam ls -lh aligned.sorted.bam*
samtools flagstat aligned.sorted.bam samtools view aligned.sorted.bam chr1:1000-1100 | wc -l
samtools depth -a aligned.sorted.bam | awk '{sum+=$3} END {print "mean depth:", sum/NR}'
samtools coverage aligned.sorted.bamWhat you should see
36 reads overlap chr1:1000-1100; mean depth is about 14.6; and samtools coverage reports 99.79% of the chromosome covered.
Check your understanding
chr1:1000-1100 rely on?Sources & further reading
- Li H, Handsaker B, Wysoker A, et al. The Sequence Alignment/Map format and SAMtools. Bioinformatics 25: 2078-2079, 2009. doi:10.1093/bioinformatics/btp352
- Danecek P, Bonfield JK, Liddle J, et al. Twelve years of SAMtools and BCFtools. GigaScience 10: giab008, 2021. doi:10.1093/gigascience/giab008
- Bonfield JK, Marshall J, Danecek P, et al. HTSlib: C library for reading/writing high-throughput sequencing data. GigaScience 10: giab007, 2021. (BAM, CRAM and indexes) doi:10.1093/gigascience/giab007
Last reviewed: October 2026.
Variant calling: from FASTQ to VCF โ
Practice terminal powered by sandbox.bio (runs in your browser; your commands stay on your computer).