How to View a BAM File

By Dr. Zubair Khalid, DVM, MS, PhD ·

How to View a BAM File

You can view a BAM file in three complementary ways. At the command line, samtools view turns alignments into readable text. samtools tview opens an interactive terminal browser. IGV draws alignments, coverage, and variants in a graphical window. By the end of this guide you will have run all three, confirmed that the file is intact, and learned to recognize the indexing and reference mismatches that make reads vanish from a viewer.

You need a BAM file, its index, a reference FASTA that matches the reference used for alignment, samtools, and IGV if you want the graphical route. A working terminal and roughly the same amount of free disk as the BAM file are useful when you convert formats. Nothing here requires programming, but you will type commands and read tab-delimited output.

What a BAM File Actually Is

BAM stands for Binary Alignment/Map. It is the compressed binary form of SAM, the Sequence Alignment/Map text format. A BAM file holds a header and a long list of alignment records. Each record describes one sequenced read and where it aligns to a reference genome.

BAM uses BGZF compression, a block-based variant of gzip. The block structure is what makes random access possible. With an index, a tool can jump to a genomic region without decompressing the entire file. Without an index, the same tool must stream from the start.

The header is made of lines that begin with @. The @HD line records the SAM version and sort order. Each @SQ line defines one reference sequence, with a name in SN and a length in LN. The @RG line describes a read group. The @PG line records the program and command line used to produce the file. The @SQ names are critical. If a BAM says chr1 and the FASTA you load says 1, the viewer may show nothing for that contig.

Every alignment record has 11 mandatory fields.

FieldMeaningExample
QNAMERead nameA00123:45:H7VLYDSX2:1:1101:1000:1000
FLAGBitwise alignment flags99
RNAMEReference sequence namechr1
POS1-based leftmost mapping position100000
MAPQMapping quality60
CIGARAlignment description50M
RNEXTReference name of the mate=
PNEXTPosition of the mate100200
TLENObserved template length200
SEQRead sequenceACGT...
QUALBase qualities, Phred+33IIII...

Optional tags follow the mandatory fields. Common ones are NM for edit distance, MD for a mismatch string, AS for alignment score, XS for a second-best score, and RG for the read group.

BAM, SAM, FASTQ, and FASTA

These four formats answer different questions. A FASTQ file stores raw sequencing reads and one quality score per base. Each record uses four lines: a header beginning with @, the sequence, a separator beginning with +, and the quality string. A FASTA file stores sequences with a header beginning with > and no per-base quality scores. FASTA is common for reference genomes, protein sequences, and consensus sequences.

SAM and BAM add alignment. They record the reference contig, the position, the CIGAR string, the mapping quality, and the mate information. A BAM file is not a replacement for FASTQ. It is a record of what an aligner decided about each read. Hard-clipped bases are removed from the stored sequence, and some pipelines modify qualities, so you cannot always reconstruct the original FASTQ exactly from a BAM.

Programs that process SAM and BAM files manipulate large data volumes, and memory management is a recognized engineering challenge for these tools [1]. A modest human BAM can run to tens of gigabytes, and a deep whole-genome BAM can run to hundreds. That size explains why viewers use indexes and why converting an entire BAM to text is a disk-intensive operation.

Before You Start: Files and Tools

Confirm four things before running a viewer.

  1. The BAM file exists and is not truncated.
  2. A BAM index exists and is newer than the BAM.
  3. The reference FASTA matches the one used for alignment, with contig names and lengths that agree with the BAM header.
  4. The FASTA has an .fai index.

Install samtools through your package manager, a Conda environment, or a release binary. Check the version first.

samtools --version

Example output:

samtools 1.19
Using htslib 1.19
Copyright (C) 2023 [Genome Research](/blog/guides/genome-research) Ltd.

Your version number will differ. Any current release supports the commands in this guide. If samtools is not found, fix your PATH before continuing.

Check the BAM file.

samtools quickcheck -v sample.bam

A valid file produces no output and returns exit status 0. The -v flag prints a message for each file that fails. You can confirm the status.

echo $?

Expected:

0

Build the index if it is missing.

samtools index sample.bam

This creates sample.bam.bai by default. For very long contigs, use -c to create a CSI index instead.

samtools index -c sample.bam

Index the reference FASTA.

samtools faidx reference.fa

This creates reference.fa.fai. Both samtools tview and many other tools need it.

The index must be newer than the BAM. If you re-sort or rewrite the BAM and forget to rebuild the index, region queries can return wrong results or fail. A quick timestamp check catches this.

ls -l sample.bam sample.bam.bai

The index time should be the same as or later than the BAM time.

View a BAM File with Samtools, tview, and IGV: Step by Step

The command line is the fastest way to inspect a BAM file. It also produces output you can save, diff, and count. Work through these steps in order.

Step 1: Read the Header

samtools view -H sample.bam

Example output:

@HD	VN:1.6	SO:coordinate
@SQ	SN:chr1	LN:248956422
@SQ	SN:chr2	LN:242193529
@RG	ID:sample1	SM:sample1	PL:ILLUMINA	LB:lib1
@PG	ID:bwa	PN:bwa	VN:0.7.17	CL:bwa mem reference.fa reads.fq

The SO:coordinate tag tells you the file is sorted by position. Region queries need coordinate sorting. If you see SO:unsorted or SO:queryname, sort the file before indexing.

samtools sort -o sample.sorted.bam sample.bam
samtools index sample.sorted.bam

The @SQ lines are your reference contract. Count them and compare the names with the FASTA.

samtools view -H sample.bam | grep '^@SQ' | wc -l
grep '^>' reference.fa | head

If the BAM uses chr1 and the FASTA uses 1, reads will not display against that reference in tview or IGV.

Step 2: Count and Summarize

samtools view -c sample.bam

Example output:

1000000

This counts alignment records, not read pairs. A paired-end file with one million records contains about five hundred thousand pairs.

samtools flagstat sample.bam

Example output:

1000000 + 0 in total (QC-passed reads + QC-failed reads)
0 + 0 secondary
0 + 0 supplementary
0 + 0 duplicates
950000 + 0 mapped (95.00% : N/A)
1000000 + 0 paired in sequencing
500000 + 0 read1
500000 + 0 read2
900000 + 0 properly paired (90.00% : N/A)
940000 + 0 with itself and mate mapped
10000 + 0 singletons (1.00% : N/A)
0 + 0 with mate mapped to a different chr
0 + 0 with mate mapped to a different chr (mapQ>=5)

Your numbers will differ. The key figures are the mapped percentage, the properly paired percentage, and the singleton count. A low mapped percentage points to a reference mismatch, contamination, or a bad library. A high singleton count points to alignment or insert-size problems.

samtools idxstats sample.bam

Example output:

chr1	248956422	500000	0
chr2	242193529	450000	0
*	0	0	50000

The columns are contig name, contig length, mapped reads, and unmapped reads. The line holds reads with no coordinate. The sum of mapped reads plus the count should equal the total from samtools view -c, allowing for small differences in how secondary and supplementary records are counted.

Step 3: Print Alignment Records as Text

samtools view sample.bam | head -n 2

Example output, wrapped here for readability:

read1	99	chr1	100000	60	50M	=	100200	250	ACGT...	IIII...
read1	147	chr1	100200	60	50M	=	100000	-250	ACGT...	IIII...

The columns are tab-separated and follow the SAM specification. Field 2 is the FLAG. Field 4 is the 1-based position. Field 5 is MAPQ. Field 6 is the CIGAR string. The dots in the sequence are not literal. They stand for bases omitted in this shortened example.

To view one region, the BAM must be indexed.

samtools view sample.bam chr1:100000-100500

If the index is missing, samtools prints a message like:

[E::idx_find_and_load] Could not retrieve index file for 'sample.bam'
samtools view: [main_samview] random alignment retrieval only works for indexed BAM or CRAM files.

Build the index and rerun.

Step 4: Filter by Flags and Mapping Quality

SAM flags are bitwise. The common values are worth memorizing.

Flag valueMeaning
1Paired
2Properly paired
4Unmapped
8Mate unmapped
16Reverse strand
32Mate on reverse strand
64First read in pair
128Second read in pair
256Secondary alignment
512Failed vendor QC
1024Duplicate
2048Supplementary alignment

Use -f to require a flag and -F to exclude one. To view only mapped reads:

samtools view -F 4 sample.bam chr1:100000-100500

To view only properly paired reads:

samtools view -f 2 sample.bam chr1:100000-100500

To require a minimum mapping quality of 30:

samtools view -q 30 sample.bam chr1:100000-100500

To count reads in a region after filtering:

samtools view -c -F 4 -q 30 sample.bam chr1:100000-100500

Streaming with samtools view avoids loading a whole BAM into memory. That matters because memory management is a known challenge in SAM and BAM software, and different implementations trade runtime against memory use [1]. Piping a full BAM through several commands is fine, but each stage holds only a buffer, not the whole file.

Step 5: Convert Between BAM and SAM

To write a SAM text file:

samtools view -h -o sample.sam sample.bam

The -h flag includes the header. Without it, you get records only.

To convert SAM back to BAM:

samtools view -b -o sample.bam sample.sam

To compress to CRAM:

samtools view -C -T reference.fa -o sample.cram sample.bam

CRAM stores differences from a reference, so it needs the reference both to write and to read. A CRAM without its reference is not self-contained.

Converting a large BAM to SAM produces a very large text file. A 30 GB BAM can become several hundred gigabytes of text. Check free space before you run the command, and prefer piping to head or grep when you only need a few records. The data volumes involved are exactly why SAM and BAM tooling requires careful memory management [1].

Step 6: Check Your Work

Run three checks.

samtools quickcheck -v sample.bam
samtools view -c sample.bam
samtools idxstats sample.bam

The total count should match the sum of the idxstats mapped column and the * unmapped count. If it does not, you may be counting secondary or supplementary alignments differently. Add -F 0x900 to exclude secondary and supplementary records and compare again.

samtools view -c -F 0x900 sample.bam

A known variant is a good biological check. Pick a position with a variant you trust, view it in samtools and in IGV, and confirm that the same reads and the same base counts appear.

View a BAM File in Samtools tview

samtools tview is an interactive terminal viewer. It needs a BAM, an index, and a reference FASTA. Start at a region.

samtools tview sample.bam reference.fa -p chr1:100000

The screen has a reference track at the top, a coverage row, and aligned reads below. Matching bases are shown as dots, mismatches as letters, deletions as gaps, and insertions as extra characters. Colors mark bases, read strands, or quality depending on the build.

The essential keys are few.

KeyAction
gGo to a genomic location
?Show help
qQuit
Arrow keysScroll
rToggle read names
sToggle sequence display

Press g, type a locus such as chr1:100000, and press Enter. The display jumps to that position.

tview reads the BAM through its index, so region navigation depends on a valid .bai or .csi file. It reads the FASTA through its .fai, so a missing FASTA index produces an error at startup.

samtools faidx reference.fa

If tview reports that it cannot open the reference, check the path and the .fai. If it reports that it cannot retrieve an index, build the BAM index. If the screen shows reads but no reference bases, the FASTA contig names probably do not match the BAM header.

tview is best for quick checks at the command line, especially on remote servers. It is not a publication graphics tool. For figures, use IGV or a scripted plotting library.

View a BAM File in IGV

IGV, the Integrative Genomics Viewer, is a graphical browser from the Broad Institute. It loads a genome, then a BAM, and draws alignments, coverage, and optional variant calls.

Load the Genome

Download and launch IGV. Then choose Genomes > Load Genome from File and select your reference FASTA. IGV builds or loads a .fai and a .2bit or equivalent index as needed. For common assemblies, you can instead choose a built-in genome from the Genomes menu, but the contig names must match the BAM header.

Load the BAM

Choose File > Load from File and select sample.bam. IGV looks for sample.bam.bai and loads it automatically. If no index exists, IGV may offer to create one with igvtools, or you can build it first.

samtools index sample.bam

Load the BAM after the genome. Loading a BAM against the wrong genome is the most common reason for an empty display.

Navigate to a Locus

Type a locus in the search box at the top, for example chr1:100,000-100,500, and press Enter. IGV accepts commas in coordinates. You can also type a gene symbol if the loaded genome has an annotation track.

Zoom with the + and - buttons or the zoom slider. At whole-genome view, individual reads are not drawn. Zoom in until the alignment track shows reads.

Adjust the Display

Right-click the alignment track to change settings. Useful options include:

  • Color alignments by to switch between strand, pair orientation, insert size, and tag.
  • Sort alignments by to sort by base, strand, mapping quality, or read name.
  • Show coverage track to display depth.
  • Downsample to limit the number of reads drawn.

The coverage track shows depth at each base. The alignment track shows individual reads. The sashimi track, if enabled, shows splice junctions. For RNA-seq data, the sashimi view is often more informative than the read view.

IGV downsamples by default when coverage is high. The displayed read count is not the true read count. If you need exact allele fractions, use samtools mpileup or samtools view -c on the region, not the visual impression from a downsampled track.

Large BAM files load slowly over a network. Indexed access helps, but the initial header read and the first region query still transfer data. The underlying data volume is the same one that makes command-line processing memory-sensitive [1].

Reading What You See

A few fields carry most of the interpretive weight.

FLAG. The flag tells you paired status, strand, mapping status, and duplicate status. A read with flag 4 is unmapped. A read with flag 1024 is a duplicate. A read with flag 256 is a secondary alignment. Filter these before counting.

MAPQ. Mapping quality is a Phred-scaled confidence that the read is placed correctly. Values run from 0 to 255. A value of 0 means the read maps equally well to multiple places. A value of 255 means mapping quality is unavailable. The scale is aligner-specific, so do not compare MAPQ 60 from BWA with MAPQ 60 from a different aligner without checking the documentation.

CIGAR. The CIGAR string describes the alignment. 50M means 50 aligned bases. 10S40M means 10 soft-clipped bases followed by 40 aligned bases. 20M5D30M means a 5-base deletion. 100N means a skipped region, typical of RNA-seq introns. Soft-clipped bases remain in the sequence. Hard-clipped bases are removed.

Insert size. TLEN is the observed template length. In a paired-end library, unusual insert sizes flag structural variants or mapping errors. IGV colors pairs by insert size when you select that option.

Tags. NM is the edit distance to the reference. MD describes mismatches and deletions. AS is the alignment score. RG identifies the read group, which matters for duplicate marking and base quality recalibration.

Key Commands at a Glance

GoalCommandNotes
Check integritysamtools quickcheck -v sample.bamSilent on success
Read headersamtools view -H sample.bamShows @SQ contigs
Count recordssamtools view -c sample.bamIncludes secondary and supplementary
Summary statssamtools flagstat sample.bamMapping and pairing rates
Per-contig countssamtools idxstats sample.bamMapped and unmapped per contig
View a regionsamtools view sample.bam chr1:1000-2000Needs an index
Exclude unmappedsamtools view -F 4 sample.bamKeeps mapped reads
Require proper pairsamtools view -f 2 sample.bamKeeps properly paired reads
Minimum MAPQsamtools view -q 30 sample.bamDrops low-confidence alignments
Convert to SAMsamtools view -h -o out.sam sample.bam-h keeps the header
Convert to BAMsamtools view -b -o out.bam in.samBinary output
Index BAMsamtools index sample.bamCreates .bai
Index FASTAsamtools faidx reference.faCreates .fai
Terminal viewersamtools tview sample.bam reference.faAdd -p for a locus
Graphical viewerIGVLoad genome, then BAM

Common Mistakes and Limitations

Opening a BAM in a text editor. A BAM is binary. A text editor shows garbled characters or refuses to open it. Use samtools view to see text.

Forgetting the index. Region queries and both viewers need an index. samtools view sample.bam without a region works without one because it streams the file. samtools view sample.bam chr1:1000-2000 does not.

Indexing an unsorted BAM. samtools index requires coordinate sorting. If the file is unsorted, the command reports unsorted positions and fails. Sort first with samtools sort.

Using a stale index. If you rewrite a BAM and keep the old .bai, region queries can return wrong reads. Rebuild the index after every rewrite.

Loading the wrong reference. Contig names must match exactly, including chr prefixes. A BAM aligned to chr1 will not display against a FASTA that names the contig 1. Check the @SQ lines.

Ignoring the .fai. tview and IGV need a FASTA index. Without it, the reference track fails or the browser stalls while building one.

Assuming IGV shows every read. Downsampling is on by default at high coverage. The visual allele fraction can differ from the true fraction. Use samtools for exact counts.

Confusing SAM and BAM. SAM is text and BAM is binary. They hold the same information, but only SAM is human-readable. A .sam file can be opened in a text editor. A .bam file cannot.

Confusing BAM with FASTQ or FASTA. BAM holds aligned reads. FASTQ holds raw reads with qualities. FASTA holds sequences without qualities. None is a substitute for another.

Forgetting that CRAM needs a reference. CRAM is reference-based compression. Reading a CRAM without the correct FASTA fails or produces incorrect sequence. Use -T reference.fa with samtools.

Treating MAPQ 255 as a high score. 255 means unavailable, not perfect. Check the aligner's convention.

Mixing coordinate conventions. SAM and BAM POS fields are 1-based. BED files are 0-based half-open. A one-base offset causes off-by-one errors when you compare regions across formats.

Assuming a variant is real because IGV shows it. Strand bias, low complexity, and misalignment produce apparent variants. Check the flag counts by strand, the mapping quality, and the alignment in tview before trusting a call.

Underestimating memory and disk. Converting a large BAM to SAM, sorting it, or loading it into a graphical browser all stress memory and disk. SAM and BAM tools are built around these constraints, and memory management is a recognized challenge in their implementation [1]. Work on regions when you can, and use streaming pipelines when you cannot.

Skipping the integrity check. A truncated BAM can open partially and mislead you. samtools quickcheck -v takes seconds and catches the common failure.

Frequently Asked Questions

Can I open a BAM file in a text editor?

No. BAM is a binary compressed format, so a text editor shows unreadable bytes. Use samtools view sample.bam to print records as SAM text.

Do I need an index to view a BAM file?

You need an index for region queries and for graphical browsers such as IGV. You do not need one to stream every record from start to finish with samtools view sample.bam.

What is the difference between SAM and BAM?

SAM is the tab-delimited text format. BAM is the compressed binary form of the same data. They carry the same alignment information, but only SAM is readable in a text editor.

Is a BAM file the same as a FASTQ file?

No. FASTQ stores raw reads and per-base quality scores with no alignment. BAM stores reads after alignment, with coordinates, flags, CIGAR strings, and mapping qualities.

Why does IGV show no reads for my BAM?

The usual causes are a missing index, a genome whose contig names do not match the BAM header, or a zoom level that is too far out. Load the correct genome, build the index, and zoom to a specific locus.

How do I view a specific region of a BAM file?

Use samtools view sample.bam chr1:1000-2000 after indexing the file. In tview, press g and type the locus. In IGV, type the locus in the search box.

What does MAPQ 255 mean?

MAPQ 255 means mapping quality is unavailable for that read. It does not mean the read maps perfectly. Check the aligner documentation for how the value is assigned.

Can I view a BAM file without a reference genome?

You can read the records with samtools view without a reference. tview and IGV can display reads, but the reference track and mismatch coloring need a matching FASTA.

Sources

  1. Comparing Ease of Programming in C++, Go, and Java for Implementing a Next-Generation Sequencing Tool.