1

I have some logs syntax. For example if I got error I get something like this:

[ERROR] You get error here

How I can intercept terminal (ubuntu for example) and color this text?

itdxer
  • 1,236
  • 1
  • 12
  • 40
  • this answer could help you http://stackoverflow.com/questions/17177174/how-to-color-linux-terminal-foreground-and-background-text – LMC Oct 24 '13 at 17:50
  • 2
    this one looks even better http://stackoverflow.com/questions/2616906/how-do-i-output-coloured-text-to-a-linux-terminal?rq=1 – LMC Oct 24 '13 at 17:51

1 Answers1

1

You can do something like this:

## Color coded message
ERR=$(printf "%-25s" "$(echo -e "\033[1;31m[ ERROR ]\033[0m")")
OKY=$(printf "%-25s" "$(echo -e "\033[1;32m[  OK   ]\033[0m")")
WRN=$(printf "%-25s" "$(echo -e "\033[1;33m[ WARN  ]\033[0m")")
INF=$(printf "%-25s" "$(echo -e "\033[1;36m[ INFO  ]\033[0m")")

echo -e "${ERR}You get error here!!"
echo -e "${OKY}This is a success!!"
echo -e "${WRN}You have been warned!!"

Hope it helps. Cheers!!


w.r.t your second question, change the code like this to color the entire line:
ER="\033[0;31m"
OK="\033[0;32m"
WR="\033[0;33m"
IN="\033[0;34m"
NC="\033[0m"
#
echo -e "${ER}[ERROR] You get Error here!!${NC}"
echo -e "${OK}[OKAY ] This is a Success!!${NC}"
echo -e "${WR}[WARN ] You have been Warned!!${NC}"
echo -e "${IN}[INFO ] You have been Informed!!${NC}"

or, create a function() something like this:

function txtColor()
{
    local typ="$1"
    local msg="${@:2}"

    if [ $typ == "ER" ]; then
        echo -e "\033[0;31m[ ERROR ]  ${msg}\033[0m"
    elif [ $typ == "OK" ]; then
        echo -e "\033[0;32m[ OKAY  ]  ${msg}\033[0m"
    elif [ $typ == "WR" ]; then
        echo -e "\033[0;33m[ WARN  ]  ${msg}\033[0m"
    elif [ $typ == "IN" ]; then
        echo -e "\033[0;34m[ INFO  ]  ${msg}\033[0m"
    else
        echo -en "\033[1;33m[ WARN  ]  Wrong message type: "
        echo -e "${typ}\033[0m\n\t   ${msg}"
    fi
}

and use it anywhere you like:

txtColor "ER" You got Error here!! 
txtColor OK "This is a success!!"
txtColor "WR" "You have been warned!!" 
txtColor OL Text without any color!!

(change the spacing ans.or type as you please) FYI, replace all the 0; with 1; if you want bold text in stead. Cheers!!

MacUsers
  • 2,091
  • 3
  • 35
  • 56
  • Thanks, that greate solution! Can I make something like that for all row? – itdxer Oct 26 '13 at 17:04
  • @itdxer: If you have added the first bit of the code at the top of your script, all you have to do is replace all the `[ERROR]`s with `${ERR}` - if that's what you mean. – MacUsers Oct 27 '13 at 07:44
  • No, I this row colored only this 7 symbols ([ERROR]), but can I make all row red for example? – itdxer Oct 27 '13 at 10:34
  • @itdxer: sure you can. See my edit in my original reply. Cheers!! – MacUsers Oct 27 '13 at 19:47