Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm a bit new to bash scripting, and I'm wondering if there is a program or built-in command to pipe to that will print in a specified color? Or is there an echo argument to do so?

Like I could do:

echo Hi | commandhere -arguement blue

and it would print "Hi" in the color blue?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

I don't know of any utility for colored printing itself, but you can do it easily with a shell function like this:

# colorize stdin according to parameter passed (GREEN, CYAN, BLUE, YELLOW)
colorize(){
    GREEN="\033[0;32m"
    CYAN="\033[0;36m"
    GRAY="\033[0;37m"
    BLUE="\033[0;34m"
    YELLOW="\033[0;33m"
    NORMAL="\033[m"
    color=\$${1:-NORMAL}
    # activate color passed as argument
    echo -ne "`eval echo ${color}`"
    # read stdin (pipe) and print from it:
    cat
    # Note: if instead of reading from the pipe, you wanted to print
    # the additional parameters of the function, you could do:
    # shift; echo $*
    # back to normal (no color)
    echo -ne "${NORMAL}"
}
echo hi | colorize GREEN

If you want to check other colors, take a look at this list. You can add support for any color from there, simply creating an additional variable at this function with the correct name and value.

share|improve this answer
    
So I just put this into the file "colorize", mark it as executable and put it into /etc/bin ? –  TenorB May 10 '12 at 23:15
    
You can just copy the function to your .bashrc. –  elias May 10 '12 at 23:17
    
Ok thanks! this helps! –  TenorB May 10 '12 at 23:19
1  
If you really want to do an executable file though, you should copy everything from within the function (inside the brackets) and put in a file "colorize", mark it as executable and put it in some directory in your $PATH variable (/usr/local/bin is a good place) –  elias May 10 '12 at 23:19
    
If you are like me and just trying to learn more about bash scripting, here's another script that does a very similar thing. Interesting to compare these two scripts. I am making my own to combine them. –  seafangs Nov 4 '12 at 23:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.