Shell Person Help me keep the shell people alive.

30Jul/091

Easily Change Text Color with BASH

fan

Here's a script to easily add color to other BASH scripts. The only trick to it is that it uses a character that I don't know how to put on the web.

NB - If you select the "view plain" link at the top of the container surrounding the script, it will open a new link with the plain text of the script. You should use this plain text. Not only does it preserve the special character the script uses to change colors, it also preserves other characters that WordPress changes (note line 5, between "cat" and "EOF"). If you don't use the "view plain" link and try to cut, but instead paste the script directly from this page, it won't work. Also, if you need to create the special character I use to make it display different colors, you can make it in gnome-terminal by pressing "ctrl+v" followed by "ctrl+[".

#!/bin/bash
## Specify color to write in using arguments

function --help {
cat << EOF

ERROR: $0 requires a color argument.

USAGE: Changes the color of the text piped into it.

These color arguments are availabe:

	ARGUMENT	SHORTCUT
	white	------	w
	red	------	r
	green	------	g
	yellow	------	y
	blue	------	b
	purple	------	p
	teal	------	t

	bold	------	bb

The "bold" argument will modify any color.
Use a max of 2 arguments (one color and bold).

EOF
}

function bold {
# make the color bold
BOLD=1\;
}

function white {
COLOR=1
}

function red {
COLOR=31
}

function green {
COLOR=32
}

function yellow {
COLOR=33
}

function blue {
COLOR=34
}

function purple {
COLOR=35
}

function teal {
COLOR=36
}

## shortcuts
function bb {
bold
}
function w {
white
}
function r {
red
}
function g {
green
}
function y {
yellow
}
function b {
blue
}
function p {
purple
}
function t {
teal
}

## Execution

if [ "$#" = 0 ]
then
--help
fi

while (($#));
	do
		$1
		shift
	done

echo -n "["$BOLD""$COLOR"m"
cat
echo -n ""

Here's a link to an example of what it looks like in action. Note that the input must be piped into the script.

Comments (1) Trackbacks (0)
  1. Good idea, but needs to replace this at the end of the script to work in all platform:

    echo -ne “\e[“$BOLD””$COLOR”m”
    cat
    echo -ne “\e[0m”


Leave a comment

No trackbacks yet.