I'm aware of libraries in languages such as Ruby and Javascript to make colorizing your terminal scripts easier by using color names like "red".

But is there something like this for shell scripts in Bash, or Ksh, or whatever?

  • 8
    please mark an answer as correct... you only marked 1 out of your total 46 asked questions so far! – m13r Aug 8 '14 at 11:04

You can define colours in your bash scripts like so:


And then use them to print in your required colours:

printf "%s\n" "Text in ${red}red${end}, white and ${blu}blue${end}."

You can use tput OR printf

Using tput ,

just create function as below and use them

shw_grey () {
    echo $(tput bold)$(tput setaf 0) $@ $(tput sgr 0)

shw_norm () {
    echo $(tput bold)$(tput setaf 9) $@ $(tput sgr 0)

shw_info () {
    echo $(tput bold)$(tput setaf 4) $@ $(tput sgr 0)

shw_warn () {
    echo $(tput bold)$(tput setaf 2) $@ $(tput sgr 0)
shw_err ()  {
    echo $(tput bold)$(tput setaf 1) $@ $(tput sgr 0)

you can call above function using shw_err "WARNING:: Error bla bla"

Using printf

print red; echo -e "\e[31mfoo\e[m"
  • 2
    echo -e isn't printf, and also needs a warning that it differs from the tput option in that it doesn't automatically adapt to suit $TERM. – Toby Speight Oct 20 '17 at 10:48

In zsh:

autoload -U colors

echo $fg[green]YES$fg[default] or $fg[red]NO$fg[default]?

For simple common uses (full line of text in a single color only, with trailing newline) I modified jasonwryan's code as follows:



printf "$green"   "This is a test in green"
printf "$red"     "This is a test in red"
printf "$yellow"  "This is a test in yellow"
printf "$blue"    "This is a test in blue"
printf "$magenta" "This is a test in magenta"
printf "$cyan"    "This is a test in cyan"
  • Or in Awk, modified slightly: awk -v red="$(printf '\e[1;31m%%s\e[0m\\n')" -v green="$(printf '\e[1;32m%%s\e[0m\\n')" 'BEGIN { printf red, "This text is in red"; printf green, "This text is in green" }' – Wildcard Oct 13 '17 at 3:52

Better is to use tput which will handle escape characters depending on the output / terminal capabilities. (If a terminal cannot interpret \e[* color codes, then it will be "polluted" which makes output harder to read. (Or sometimes, if you grep such output, you will see those \e[* in the results)

See this tutorial for tput.

You can write :

blue=$( tput setaf 4 ) ;
normal=$( tput sgr0 ) ;
echo "hello ${blue}blue world${normal}" ;

Here is a tutorial to print a colored Clock in the terminal.

Also, note that tput may still prints escape character when redirecting STDOUT to a file:

$ myColoredScript.sh > output.log ;
# Problem: output.log will contain things like "^[(B^[[m"

To prevent this to happen, setup your tput variables like proposed in this solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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