Kaje
Kaje

Reputation: 851

Shell script to identify colored console output

I need to identify whether my terminal prints colored output or not using bash scripts. Is there any direct shell command to do this? How can I do this?

My main goal is to identify whether the output matches with the default font color of terminal or not. If it's not matching, I should write an alert message in a text file.

Upvotes: 4

Views: 361

Answers (2)

Jeff Bowman
Jeff Bowman

Reputation: 95704

Control characters are output characters as well, so you can detect their sequences similar to this answer.

if printf "\x1b[31mRed\x1b[0m" | grep -Pq "\\x1b\[[0-9;]+m"; then
  echo colored
else
  echo uncolored
fi
  • printf supports outputting control sequences. If you use echo, you'll need -e.
  • grep -q will suppress printing and just exit 0 (success) if it finds a match, and nonzero (failure) if it doesn't.
  • You'll need -P (PERL regular expressions) on grep for it to interpret the control sequence, because POSIX regular expressions don't support escape characters. Note the double-backslash in \\x1b, meaning you're letting grep handle the escape instead of your shell. Perl regular expressions are supported in GNU grep but seem not to be supported in BSD (including Mac OS X).

Some scripts only use control characters if they detect the input is tty-like, so you may want to use the script command to capture output including control characters directly to a file.

Upvotes: 1

Zombo
Zombo

Reputation: 1

The way I do it is by searching for the Escape Sequence, followed by the color code, example

# red
awk '/\033\[31m/'

Example

Upvotes: 0

Related Questions