Neat trick: colorize bash input

As a frequent technical communicator, I often want to cut-and-paste something from my Unix terminal sessions so that other people can see what I’m seeing.

Unfortunately, it can be confusing to read:

Hello World in the Unix shell, without color

Hello World in the Unix shell, without color

Instead I want it to look like this:

Hello World in the Unix shell, in color

Hello World in the Unix shell, in color

How did I make this happen? Well, it’s a bit hacky, and it only works with the bash shell. Read on for more details.

What’s happening here is we’re actually setting the color to yellow (and the font as bold) right at the end of the prompt, and using Bash’s “debug trap” to reset it before running the subsequent command.

To make this work, add the following lines to your .bashrc file:
# Awesome color trick for bash: set color to yellow in our prompt
# Use trap debug to set it back before running the command in question
export PS1="\[$(tput sgr0)\]${PS1}\[$(tput bold setaf 11)\]"
trap 'tput sgr0' DEBUG

The first command wraps the existing shell prompt (PS1) with two tput commands. The first resets the terminal to its default setting, and the second sets yellow and bold.  You may need to play around with tput on your particular platform to find a pleasing color for your environment.

(What are the backslash-escaped brackets around the tput commands in the shell prompt? They’re used to identify non-printing strings; that is, text which doesn’t advance the column number. I presume that bash needs this information to deal with line wrapping, but haven’t experimented or read the code to be sure.)

The trap command is a shell built-in. Normally, trap can be used to run specific code when the bash process receives a signal. (You could use it to build a HUP handler in a shell script, for example.) The special DEBUG value (which replaces the signal name or number) runs after every command.

In fact, the DEBUG trap handler runs after “every simple command,” which means that there’s occasional font color weirdness when running subshells. For me, that’s a small price to pay to improve screenshots and cut-and-pasted shell examples.