3

The program I'm working on has an option to enable/disable the color codes in it's output.

I want to test if this feature works as expected. This is what I tried:

$ myprogram | grep -q '\e[32m' # testing for green color
$ myprogram | grep -q '\e'
$ myprogram | grep -q '\033'

I also tried the same commands with double backslashes and without quotes.

But none of this works.

How can test if my program output contains any color codes?

1
  • Do you only want to know about sequences that change the foreground colour? Or any sequence that affects colouring (background, foreground, cursor, palette, etc.). Do you also care for also character attributes (reverse video, bold, underline, italic, standout...)? Commented Jul 20, 2020 at 10:46

2 Answers 2

4

The grep command, with both its BRE and ERE variants, does not recognise a sequence representing ESC. You need either to use the perl extension (GNU grep -P) or match on a fixed shell string.

# string with shell formatting, grep uses fixed string match
( tput setaf 2; echo Green text; tput op ) | grep -Fq $'\033[32' && echo found green
found green

# grep uses Perl's PCRE match to match any colour (change "\d+" to "32" for just green)
( tput setaf 2; echo Green text; tput op ) | grep -Pq '\033\[\d+[;m]' && echo found a colour
found a colour

If your shell supports $'...string here...' formatting of strings, and you only need to match for a specific colour, I'd recommend you take that option.

2
  • Thank you! For some reason I need to use a slightly different search string: '\033\[\d+;' but otherwise it works perfect!
    – ph_0
    Commented Jul 17, 2020 at 15:00
  • 1
    Ah yes. I'd forgotten codes can be chained. Even matching on ; isn't perfect but if it works for your application that's good enough Commented Jul 17, 2020 at 15:12
0

Another thing you can do is use 'tr' to turn the escape character into something else, especially if there is a character like ^ or % or even ^A (control-A), which grep does seem to be happy with:

boldfoo=$(printf "not bold \033[1mfoo\033[m not bold")

echo $boldfoo
echo $boldfoo | tr '\033' '\001' | grep ^V^A  # Type <Ctrl-V><Ctrl-A>
# Use the return value from this to see whether there are escape characters in $boldfoo.

I have used this trick to use sed/grep to find multiline patterns -- turn into ^A, and then match on a pattern with ^A, etc. Takes some finagling as the entire input is now a single line, but it works with some effort.

1
  • 1
    You could use Ctrl/V ESC to add a literal Escape code into grep, and avoid the tr Commented Jul 19, 2020 at 16:16

You must log in to answer this question.

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