Syntax highlighting in terminal

Syntax highlighted cat

I was just quickly flipping through code on a terminal and got to thinking that it would be pretty handy to be able to syntax highlight when using head or grep without having to open an editor. Luckily, I remembered Pygmentize was pretty handy when syntax highlighting in LaTeX so I wondered if they had an equivalent output for terminal. It turns out they do (in standard or 256 color no less) so in a couple minutes I had a really short script for highlighting code at the terminal saved it to bin/ccat and was ready to go. Pygmentize really is impressive. Here's the script if anyone else is looking to do the same:

BASH:
  1. #!/bin/bash#!/bin/bash
  2. if [ ! -t 0 ];then
  3.         file=/dev/stdin
  4. elif [ -f $1 ];then
  5.         file=$1
  6. else
  7.         echo "Usage: $0 code.c"
  8.         echo "or e.g. head code.c|$0"
  9.         exit 1
  10. fi
  11. pygmentize -f terminal -g $file

It just looks for stdin and if it doesn't find it it looks for a file name or takes direct input. Obviously it requires Pygmentize (which is really easy to install if you already have Python).