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?

3 Answers 3

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
1
  • Indeed thanks. I browsed grep man page but --color[=WHEN], --colour[=WHEN] confused me, although it's explained fine
    – zetah
    Jan 29, 2012 at 23:50
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'
2
  • Yes, those lines are present, but output is unfortunately same (w/o coloring) when grep is run from bash script.
    – zetah
    Jan 29, 2012 at 23:46
  • Shell aliases only have an effect on interactive shell sessions by default. You either need to 1) add the --color option to the grep command explicitly (safe) or 2) enable the expand_aliases shell option and source ~/.bashrc (prone to issues because of possible other aliases). You can refine 1) and define a variabl GREP="grep --color=auto" and later use $GREP instead of grep everywhere in your script. Sep 8, 2016 at 14:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .