If you just want to tell
less to interpret color codes, use
less -R. ref.
You can utilize the power of pygmentize with less – automatically! (No need to pipe by hand.)
pygments with your package manager or pip (possibly called
python-pygments) or get it here http://pygments.org/download/.
Write a file
#!/bin/sh case "$1" in *.awk|*.groff|*.java|*.js|*.m4|*.php|*.pl|*.pm|*.pod|*.sh| *.ad[asb]|*.asm|*.inc|*.[ch]|*.[ch]pp|*.[ch]xx|*.cc|*.hh| *.lsp|*.l|*.pas|*.p|*.xml|*.xps|*.xsl|*.axp|*.ppd|*.pov| *.diff|*.patch|*.py|*.rb|*.sql|*.ebuild|*.eclass) pygmentize -f 256 "$1";; .bashrc|.bash_aliases|.bash_environment) pygmentize -f 256 -l sh "$1";; *) if grep -q "#!/bin/bash" "$1" 2> /dev/null; then pygmentize -f 256 -l sh "$1" else exit 1 fi esac exit 0
export LESS='-R' export LESSOPEN='|~/.lessfilter %s'
Also, you need to make
~/.lessfilter executable by running
chmod u+x ~/.lessfilter
Tested on Debian.
You get the idea. This can of course be improved further, accepting more extensions, multiple files, or parsing the shebang for other interpreters than bash. See some of the other answers for that.
The idea came from an old blog post from the makers of Pygments, but the original post doesn’t exist anymore.
Btw. you can also use this technique to show directory listings with
Try the following:
Causes “raw” control characters to be displayed. (…)
-r, but only ANSI “color” escape sequences are output in “raw” form. (…)
I got the answer in another post: Less and Grep: Getting colored results when using a pipe from grep to less
When you simply run
detects whether the output is a
terminal and if so enables colors.
However, when it detects a pipe it
disables coloring. The following
grep --color=always "search string" * | less -R
Will always enable coloring and
override the automatic detection, and
you will get the color highlighting in
Warning: Don’t put
--color=always as an alias, it break things sometimes. That’s why there is an