Skip to content
Latchkey

bat: Print Line Ranges and Diff Context

bat -r <start>:<end> prints only a slice of a file, and bat -d shows only the lines that differ from the git HEAD, both with syntax highlighting.

Beyond replacing cat, bat can quote a specific region of a file (an error site) or show just what changed, which is handy for annotating CI failure logs.

What it does

bat -r/--line-range limits output to a start:end span (open-ended forms like :20 or 40: work). --highlight-line (-H) marks a specific line. --diff (-d) restricts output to lines that git reports as changed, with a few lines of context. These combine with the usual highlighting and decoration controls.

Common usage

Terminal
bat -r 40:60 src/app.py              # only lines 40-60
bat -r :25 config.yaml               # first 25 lines
bat -H 42 src/app.py                 # highlight line 42
bat -d src/app.py                    # only git-changed lines
bat -pp -r 100:120 huge.log          # plain, no pager, a window

Options

FlagWhat it does
-r / --line-range <a:b>Print only lines a through b (open-ended allowed)
-H / --highlight-line <n>Emphasize line n (repeatable)
-d / --diffShow only lines changed vs git HEAD
--diff-context <n>Context lines around each diff hunk
-n / --numberShow line numbers without other decorations
-ppPlain output with the pager disabled

In CI

When a test reports a failure at file:line, bat -H <line> -r <line-10>:<line+10> file quotes the surrounding code into the log with the offending line marked. Always add -pp (or --paging=never) so bat does not try to page in the non-interactive environment.

Common errors in CI

An empty result from -d means there are no uncommitted changes (bat compares against git HEAD, so a clean tree shows nothing). A line range past the end of the file simply prints to EOF, not an error. As elsewhere, on Debian/Ubuntu the binary may be batcat, and forgetting -pp can hang the job on the pager.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →