Home > bash > bash – change shell colour output

bash – change shell colour output

Problem:
I wanted to have different colours for different output.

Solution:
Lets start with some examples.
Eg 1 – from chihungchan.blogspot.com

$red="\033[31m"
$green="\033[32m"
$off="\033[0m"
$echo -e "${red}Error. Unable to run command${off}"
$echo -e "${green}OK. Run successful.${off}"

Eg 2 – from unix.com

LINE=$(grep success data.log)

if [ $? -eq 0 ]
then
        printf "\033[01;32m%s\033[00m\n" "$LINE"
else
        printf "\033[01;31m%s\033[00m\n" "'success' not found in log"
fi

Explaination.
From chihungchan.blogspot.com

  • Text properties – 0(default), 1(bold), 22(not bold), 4(underlined), 24(not underlined), 5(blinking), 25(not blinking), 7(invers), 27(not invers)
  • Foreground colour – 30(black), 31(red), 32(green), 33(yellow), 34(blue), 35(magenta), 36(cyan), 37(white)
  • Background colour – 40(black), 41(red), 42(green), 43(yellow), 44(blue), 45(magenta), 46(cyan), 47(white)

So in this example
# Text property 1 (bold)
# Foreground Colour 31 (red)
# Background Colour 42 (green)
# The command below gives me Red Text in bold with a green background.

$somecolor="\033[1;31;42m" 
$echo -e "${somecolor}OK. Run successful.${off}"

shell colours

Source:
1. http://chihungchan.blogspot.com/2008/10/give-your-shell-some-colours.html
2. www.unix.com

Update (2012-06-05): Found more information on bash colors.
http://zipizap.wordpress.com/2011/09/28/quick-bash-colors/
http://zipizap.wordpress.com/2012/04/09/quick-bash-colors-2-scripting/

Update (2012-07-17):
ANSI color escape sequences

Advertisements
Categories: bash Tags:
  1. June 5, 2012 at 1:27 pm

    It may interest you this other post, about putting colors in bash scripts with functions (it’s easier than repeatedly writting those awkward escape characters)

    http://zipizap.wordpress.com/2012/04/09/quick-bash-colors-2-scripting/

    Cheers

    • June 6, 2012 at 5:05 am

      Yes it is easier to use. Thanks, I have included the link.

  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: