color in bash

I have some tcsh scripts that produce output in color, but does not work in bash. Any idea on a solution?

  echo "  \033[2;32m"
  echo "  Optional Arguments
  echo -n "\033[0m"

echo behavior varies with shell, whereas printf behavior is consistent.

printf "  \033[2;32m"
printf "  Optional Arguments"
printf "\033[0m"

for your echo script following will work, but I would recommend to use printf version

echo -e "  \033[2;32m"
echo -e "  Optional Arguments"
echo -e "\033[0m"

Ahhh. I understand. I take your advice.

---------- Post updated at 06:25 PM ---------- Previous update was at 06:17 PM ----------

what is the equivalent printf to

echo -n

where the code does not skip a line after output.

printf does not output the trailing newline, by default.

So if you do this at command line:

printf "\033[2;32mHello\033[0m"

you would see hello on console in green and the prompt right next to it.

1 Like

A full featured color script!

#!/bin/bash

[[ x${1// /} == x || ${#1} > 3 ]] && T=gYw || T=${1}

esc="\e"
reset="${esc}[0m"

echo
echo -n "            "
echo -n 4{0..7}m | sed 's# #    #g' 
echo -n "   "
echo -n 1\;4{0..7}m | sed 's# #  #g'
echo -n "   0m    "
echo {1..8}m | sed 's# #   #g'

for FG in 3{0..7} 1\;3{0..7}; do
     for((i=0; i<5-${#FG}; ++i)); do
           echo -n " "
     done
     echo -en "${FG}${esc}[${FG}m ${T} "
     i=0
     for BG in 4{0..7} 1\;4{0..7} {0..8}; do
         (( i > 16 )) && {
         echo -en "${esc}[${FG};${BG}m ${T} ${reset}"
         } || echo -en "${esc}[${FG};${BG}m  ${T}  ${reset}"
         ((++i))
     done
     echo
done
echo

Ok,
I have added some color to my prompt, but I never tried to color my command outputs. I have tried the examples above on my CentOS and Mac computers and there was no color add to the out put. What happens is the above echo statements changes my prompt and the printf puts the out put in front of my prtompt. What am I missing here?

To have you prompt showed in red, just replace the line below in /etc/bashrc to the later one:
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="\e[1;31m[\u@\h \W]\\$\e[0m "