Pretty Print Terminal Files With Bat

Added by to Tools on and tagged · shell ·

About 2 minutes to read (294 words)

Kitty Terminal Chronological Taxonomy Listings in Hugo
Pretty Print Terminal Files With Bat
Pretty Print Terminal Files With Bat
(see original image in new window)

bat is like a fancier cat for displaying file contents.

My work routine lately includes automatic generation of SQL files for database updates. That routine includes quickly skimming them to find obvious errors. I wanted something quicker than reviewing them in my editor, but fancier than the simple plain text of cat.

I have the Pygments syntax highlighting library for Python installed, so I could use pygmentize piped to less for paging:

$ pygmentize -g work.sql | less -NR

However, that is noticeably slow and most definitely not convenient. Adding an alias helped the convenience, but did nothing for the sluggishness.

bat provides what I need. It runs quick enough that I don't need to think about it, highlights code, numbers lines, indicates git changes in the margin, and feeds the result to less if there's more than you can display on one screen.

Packages are available for several Linux distributions, or you can install it via Homebrew (reminder: Homebrew works on macOS and Linux these days).

$ brew install bat

Sometimes I need to check the structure of files where whitespace matters: tab-delimited files, Makefiles, Python, stuff like that. bat -A shows whitespace and other non-printable characters displayed, though you lose syntax highlighting.

The site Makefile — oh look a trailing space!
The site Makefile — oh look a trailing space!
(see original image in new window)

Plain Text

I enjoy the formatting conveniences from bat even when examining plain text files.

bat showing a plain text file
bat showing a plain text file
(see original image in new window)

This is all I've needed bat for, but it's flexible enough to work into your everyday shell just like cat. Check out the README for ideas.