Collecting my attempts to improve at tech, art, and life

Pretty Print Terminal Files With Bat

Tags: shell tools


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!

Plain Text

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

bat showing a plain text file

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.

Got a comment? A question? More of a comment than a question?

Talk to me about this page on: mastodon

Added to vault 2024-01-15. Updated on 2024-04-14