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.