Home > Bash, Programming > Print color in shell terminal

Print color in shell terminal

Sometimes you might want to print something with color in a text terminal (by color I mean something other than the default text color). Put the following shell function to your ~/.bash_profile and you are go to good.

cecho() {
    case $2 in
        red) code=31;;
        blue) code=34;;
        green) code=32;;
        cyan) code=36;;
        purple) code=35;;
        brown) code=33;;
        white) code=37;;
        *) code=30;;
    esac
    printf "\e[01;${code}m$1\e[0m\n"
}

Some examples:

cecho hello cyan
cecho "something needs your attention" brown
cecho "there's something terribly wrong, have to abort now" red
cecho "this looks so pale" white
cecho "will purple work too?" purple
cecho goodbye blue

The above commands should output something like this ($TERM setting xterm-256color, tested on both OS X 10.7.2 and Ubuntu 11.10 64bit Server):

Advertisements
Categories: Bash, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: