9

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?

zetah
  • 9,871

3 Answers3

9

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
Octavian Helm
  • 14,515
3

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

#!/bin/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
done;

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

BASH Script prints with Text formating and  COLORS

0

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'