Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When I execute grep from within gnome-terminal, I get colored output - easily noticeable match, line-numbers (-n) with different colors etc

But when I execute exactly same grep command through bash script I get plane output, without coloring

Is there a way I can get colored output by using bash script?

share|improve this question
up vote 7 down vote accepted

Using the --color option works for me out when I run grep inside of shell scripts.

Here is an example of what you want.

grep -n --color=auto "PATTERN" FILE
share|improve this answer
Indeed thanks. I browsed grep man page but --color[=WHEN], --colour[=WHEN] confused me, although it's explained fine – zetah Jan 29 '12 at 23:50

Here's a small script that helps you to grap how tput works with bash

#@auth kesavan.muthuvel
#@desc - bash with colors :)

B=`tput bold`           #BOLD
D=`tput dim`            #DIM
U=`tput sgr 0 1`        #UNDERLINE
U2=`tput smul`          #UNDERLINE2
NOU=`tput rmul`         #NO UNDERLINE
H=`tput smso`           #HIGHLIGHT
X=`tput sgr0`           #RESET
C='tput setaf '         #COLOR

for i in 0 1 2 3 4 5 6 7 ; do
        c=`$C$i` && echo $c${B}I${U}always$NOU $D love \
           ${U2}colors$NOU \& $c${H}GNU/Linux$X

This will print the following output with formats like BOLD ,UNDERLINE , Highlighting and colors.

BASH Script prints with Text formating and  COLORS

share|improve this answer

Did you tried to add these alias to your ~/.bashrc?

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
share|improve this answer
Yes, those lines are present, but output is unfortunately same (w/o coloring) when grep is run from bash script. – zetah Jan 29 '12 at 23:46

Your Answer


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.