4

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.

Kaje
  • 851
  • 7
  • 18
  • I am not quite sure what you are asking but it might be answered here: ["How do I determine if a terminal is color-capable?"](http://stackoverflow.com/questions/2465425/how-do-i-determine-if-a-terminal-is-color-capable) – John1024 Oct 13 '14 at 04:41
  • IMHO, instead of _identify whether the output matches with the default font color of terminal_ would be better change the color of the output to the wanted one... – clt60 Oct 13 '14 at 08:35
  • No. It's for testing purpose. I want to confirm whether my color change get affected or not. – Kaje Oct 13 '14 at 08:44

2 Answers2

1

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.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • It should be like if printf "\x1b[31mRed\x1b[0m" | grep -pq "\\x1b\[[0-9]m"; then echo colored else echo uncolored fi – Kaje Oct 13 '14 at 08:42
0

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

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

Example

Zombo
  • 1
  • 62
  • 391
  • 407