Search code examples
grepnon-printing-characters

GREP_OPTIONS='--color=always' causes non-printing characters


My bash version:

GNU bash, version 3.2.49(22)-release (i686-pc-cygwin)
Copyright (C) 2007 Free Software Foundation, Inc.

In my .bashrc, I have:

export GREP_OPTIONS='--color=always'

To reproduce the problem, create a file test.txt and write some lines:

test1: apple
test2: orange
test3: cherry

And in bash, do a grep:

grep "test" test.txt > 1

When I check the result, I get something like this:

~ > cat -v 1
^[[01;31m^[[Ktest^[[m^[[K1: apple
^[[01;31m^[[Ktest^[[m^[[K2: orange
^[[01;31m^[[Ktest^[[m^[[K3: cherry

Any idea about this problem? btw, I've setup fileformats=unix.


Solution

  • The characters you see correspond to codes to change the text color in the terminal. Usually you would want grep to produce color only when its output is going to an interactive terminal. To do that, change

    export GREP_OPTIONS='--color=always'
    

    to

    export GREP_OPTIONS='--color=auto'