Unix Shell: Adding color to your Bash Script!

Update: You can do this in Ruby if you’d like! See the article here: Adding colored output to your Ruby Script

Need to style some of that text in your bash script?

Well I’ve put together this handle little example script. Feel free to study it and make use of it – it’s sometimes useful to visually identify important information in the console.

Click the jump to see the code!

#!/bin/bash

# Example usage:
# echo -e ${RedF}This text will be red!${Reset}
# echo -e ${BlueF}${BoldOn}This will be blue and bold!${BoldOff} - and this is just blue!${Reset}
# echo -e ${RedB}${BlackF}This has a red background and black font!${Reset}and everything after the reset is normal text!

Colors() {
Escape="\033";

BlackF="${Escape}[30m";   RedF="${Escape}[31m";   GreenF="${Escape}[32m";
YellowF="${Escape}[33m";  BlueF="${Escape}[34m";    Purplef="${Escape}[35m";
CyanF="${Escape}[36m";    WhiteF="${Escape}[37m";

BlackB="${Escape}[40m";     RedB="${Escape}[41m";     GreenB="${Escape}[42m";
YellowB="${Escape}[43m";    BlueB="${Escape}[44m";    PurpleB="${Escape}[45m";
CyanB="${Escape}[46m";      WhiteB="${Escape}[47m";

BoldOn="${Escape}[1m";      BoldOff="${Escape}[22m";
ItalicsOn="${Escape}[3m";   ItalicsOff="${Escape}[23m";
UnderlineOn="${Escape}[4m";     UnderlineOff="${Escape}[24m";
BlinkOn="${Escape}[5m";   BlinkOff="${Escape}[25m";
InvertOn="${Escape}[7m";  InvertOff="${Escape}[27m";

Reset="${Escape}[0m";
}

# Example:

# Call the function...
Colors;

# Output test code.
echo -e ${RedF}This text will be red!${Reset};

In the code above – there are examples.

So let’s walk through some examples:

  • So if I wanted to echo out some red test I would say:

    echo ${RedF}This text will be red!${Reset}

    The ${RedF} starts the coloring and the ${Reset} stops the coloring and changes all proceeding styling to the system default.

  • If I wanted to echo out some blue text that’s bold I could do:

    echo ${BlueF}${BoldOn}This will be blue and bold!${BoldOff} - and this is just blue!${Reset}

    ${BoldOn} starts the bold font styling and ${BoldOff} ends the styling.

  • If I wanted to echo out black text on a red background I could do:

    echo ${RedB}${BlackF}This has a red background and black font!${Reset}and everything after the reset is normal text!

    Notice that the formatting is set up like this: ColorF or ColorB – F is for font and B is for background.

These coloring variables are very useful for making things easily read as well as making everything more pleasing to the eye.

Enjoy!

Leave a Reply