1

I am trying to detect if a command I run in a bash script outputs in a specific color to the terminal. I have some print statements in my Java code that outputs in specific colors depending on the contents of the output.

This is done using this code:

//ANSI color codes for output
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_RESET = "\u001B[0m";

System.out.println(ANSI_GREEN + "This prints in the color green." + ANSI_RESET);

Is there a way to detect this difference in color in bash? I want to be able to stop the bash script if the output is red or continue if it remains green. If anyone knows a way to do this that would be greatly appreciated.

Thanks

BlueMoose
  • 117
  • 11

1 Answers1

1

The literal characters are available for matching using the regular tools; it's just the terminal when actually displaying the characters that removes them and changes the display color instead.

output=$(javaprog)
if [[ $output == $'\e[32mThis prints in the color green.\e[0m' ]]; then
    echo "Detected green output"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681