Alan McKinnon wrote:
> On Friday 08 May 2009 16:01:14 Mike Kazantsev wrote:
>> On Fri, 8 May 2009 14:38:58 +0100
>>
>> Stroller <strol...@stellar.eclipse.co.uk> wrote:
>>> To find the part to which I refer you'll need to scroll down about
>>> halfway through that page to "Colorize grep"; the author advises adding:
>>>
>>>    if echo hello|grep --color=auto l >/dev/null 2>&1; then
>>>      export GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'
>>>    fi
>>>
>>> to ~/.bashrc
>>>
>>> Why does he echo hello, please?
>> Some greps (like BSD one) might not support '--color' option, so "echo
>> hello|grep --color=auto l" will return error code, skipping if clause,
>> and won't break grep operation by adding an unsupported option.
> 
> except that STDERR is combined with STDOUT and sent to /dev/null so the 
> script 
> will never get it, the if is always true and the entire check is redundant. 
> Better would be
> 
> if echo hello|grep --color=auto l >/dev/null ; then
> 

The redirection of output doesn't affect the return code of grep in the
above case.

Grep's return code is determined by matching 'l' against the output of
echo hello.

The desired effect of the above code is to evaluate if the --color
option is supported by grep on the system.

The STDERR and STDOUT redirection is an attempt to not pollute the
systems screen when performing that test.

To illustrate:

1. A system that supports --color

$ if echo hello|grep --color=auto l >/dev/null 2>&1; then  echo "Grep
returned : $?"; else echo "Grep returned : $?"; fi
Grep returned : 0

2. A system that doesn't support --color (simulated by supplying
--unspported as an option to grep)

$ if echo hello|grep --unsupported l >/dev/null 2>&1; then  echo "Grep
returned : $?"; else echo "Grep returned : $?"; fi
-bash: echo: write error: Broken pipe [1]
Grep returned : 2


3. Just to complete the examples, the result of grep not matching echo's
output but still supporting the --color option. (achieved by search
"hello" for the letter 'z')

$ if echo hello|grep --color z >/dev/null 2>&1; then  echo "Grep
returned : $?"; else echo "Grep returned : $?"; fi
Grep returned : 1


Regards,
Carlos

[1] The reason an error message is shown here is because it's bash
that's reporting the broken pipe error.  Grep's error message was
redirected to /dev/null, which was:

grep: unrecognized option '--unsupported'
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

So even when the system doesn't support --color, that original code will
pollute the screen with bash's error message.

Reply via email to