Sometimes it’s nice to be able to change the text, or foreground, color when working with shell scripts or the Linux command line. This is a useful trick as it allows us to make the text more readable and the output more interesting. This can be done using ansi escape codes. Let’s take a look at a quick example. If we wanted to echo ‘this is the color red’, whilst making the word red appear red, we could use:
echo "This is the color \e[31mRed"
The \e[31m
characters are setting the text color to red, which will apply to subsequent characters in the echo. Now, this can look a little messy to read, so we could also store the character sequence in a variable, then use that in the echo command instead. For example:
RED='\033[0;31m'
echo "This is the color ${RED}Red"
Another useful one to know is how to set it back so that no colour is applied. This is useful if we are trying to add color to a single word in the middle of a sentence:
RED='\033[0;31m'
NC='\033[0m' # No Color
echo "This is the color ${RED}Red${NC}. This is my favourite color"
What if you don’t want to use red I hear you say. Well, you can select from the following table!
Black 0;30 Dark Gray 1;30
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
Cyan 0;36 Light Cyan 1;36
Light Gray 0;37 White 1;37
For example, to use Cyan you could use the following – CYAN=’\033[0;36m’.
Now this isn’t the only method – using ANSI escape codes generally works fine, but there are other ways. One such alternative is to the use tput
command. Lets take a look at an example of what this might look like in a shell script:
#!/bin/sh
RED_FG=`tput setaf 1`
GREEN_BG=`tput setab 2`
NC=`tput sgr0`
echo "${RED_FG}${GREEN_BG}Hello world${NC}"
This approach is using the tput setaf and setab commands to set the foreground and background. This is a little more readable that when using the ANSI escape codes. Hopefully this has given you some ideas of how you can inject some color into your shell scripts.