Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does grep lose colored output when executed from a bash script? [duplicate]

Tags:

grep

bash

colors

Possible Duplicate:
grep loses coloring when run from bash script

I have a simple bash script to print a header on top of my grep results:

#!/bin/bash

for var in "$@"
do
    if [[ $var != -* ]];
    then
        break 
    fi
done

echo
echo -en "\e[1;31m     ====== GREP $var ======\e[0m\n"
echo

grep $@

But the final command is somehow not the same as actually running grep from the prompt directly, because the colors are missing from the results. When executing grep directly, the results show filenames in purple and matches in red, but now all the output is the normal terminal text color. Can someone tell me how to get the colored version from my script?

like image 472
Byron Hawkins Avatar asked Sep 07 '12 16:09

Byron Hawkins


People also ask

What does grep return if no match?

If there's no match, that should generally be considered a failure, so a return of 0 would not be appropriate. Indeed, grep returns 0 if it matches, and non-zero if it does not.

How do I reduce grep output?

The quiet option ( -q ), causes grep to run silently and not generate any output. Instead, it runs the command and returns an exit status based on success or failure. The return status is 0 for success and nonzero for failure.


Video Answer


2 Answers

Looks like grep does not produce colors when not in interactive mode. You can force it to produce colored output:

grep --color=always $@
like image 184
perreal Avatar answered Oct 17 '22 17:10

perreal


Grep has 3 color modes, Auto, Always, and Off.

Auto strips out the codes when it's connected to a non interactive output, such as a pipe (if you want to see why, try redirecting the output of grep --color=always into a file and then look at the file.. control codes everywhere)

like image 10
Mikey T.K. Avatar answered Oct 17 '22 17:10

Mikey T.K.