Blog is moving

My blog is moving to http://victormendonca.com/blog/. If you are looking for a specific or older post you are in the right place Otherwise check out my new page for more up to date content.

Thursday, November 1, 2012

Playing with terminal colors on your script

Most Linux shells include support for color (font and background), which can be used in many different ways. Today I will show how to change font color based on the output of a script. This way you can have colorful outputs depending on the exit code.

Here are the two example outputs of the script (function) we will be using. It simply checks if Apache is running and returns the color coded status:

$ isApacheUp 
Apache is running

$ isApacheUp 
Apache is NOT running

Finding the mapping for the color codes is also quite easy. I will be providing some of the basic colors, but you can also try this really cool site to find additional color and background mapping - Google.

The basic usage for setting up the color is:

- Sets color (this case, white)
$ echo -e "\e[01;37m"

- Reverts color back to default
$ echo -e "\e[00m"

So if you want to change your terminal to other color, you can:

victor@Desktop:~$ echo -e "\e[00;34mPrompt to blue"
Prompt to blue
victor@Desktop:~$ echo -e "\e[00;31mPrompt to red"
Prompt to red
victor@Desktop:~$ echo -e "\e[00mPrompt to default"
Prompt to default
victor@Desktop:~$ 

Note that the color changes happens after you enter the code. So if you only want to change one word you will need to prefix the word with the new color code, and add the default color right after.

Here we can see the our Apache script using just that:

isApacheUp () {

# Sets the font color
GREEN='\e[00;32m'
DEFT='\e[00m'
RED='\e[00;31m'

# Checks if the Apache process is running
ps -ef | grep -i apache | grep -v grep > /dev/null ; STATUS=$?

# Changes the color depending on grep's exit code
if [[ $STATUS -eq 0 ]] ; then
  echo -e "Apache is ${GREEN}running${DEFT}"
else
  echo -e "Apache is ${RED}NOT running${DEFT}"
fi
}

Font color mapping:

Black = ”\e[00;30m”
Dark Gray = ”\e[01;30m”
Blue = ”\e[00;34m”
Light Blue = ”\e[01;34m”
Green = ”\e[00;32m”
Light Green = ”\e[01;32m”
Cyan = ”\e[00;36m”
Light Cyan = ”\e[01;36m”
Red = ”\e[00;31m”
Light Red = ”\e[01;31m”
Purple = ”\e[00;35m”
Light Purple = ”\e[01;35m”
Brown = ”\e[00;33m”
Yellow = ”\e[01;33m”
Light Gray = ”\e[00;37m”
White = ”\e[01;37m”

No comments: