简体   繁体   中英

How to detect color of text on the command line through a script?

I have a command-line program that outputs some text in different colors depending on the status. The text doesnt change on multiple calls, but its color changes.

Eg:The program outputs the text "S14789" on the console. The color of this text will be in red if the status is fail, and green if pass

I need to write a script to do some thing else depending on the color (status). Any suggestions?

As the scripts are giving one value at one time you can modify the script to change the exit values to 0 if it is pass and 1 if it is pass.

#!/bin/bash

echo "Print in green"
exit 0

$ ./script1.sh
Print in green
$ echo $?
0

The same way you can use exit 1 which return a value 1 to ? variable and you can use it to determine whether the script pass or fail.

So, here is what I did to perform tasks depending on color output:

/usr/bin/smoke is my program which outputs text in a particular color. Search for the color escape sequence and perform tasks (Thanks to @Jidder for suggesting cat -v ).

#!/bin/bash

COUNT=`/usr/bin/smoke | cat -v | fgrep "^[[32" | wc -l`
if [ $COUNT -gt 0 ] 
then
    #Color found, do something
else
    #Color not found, do something else
fi

Note: 32 is for green. For other colors refer the list of escape sequences: http://wiki.bash-hackers.org/scripting/terminalcodes#general_useful_ascii_codes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM