Color output of linux command similar to ‘watch -d’ to highlight differences

diff()watch

I'm at the beginning of shell scripting etc. and a bit challenged to find the proper way of colorzing a command's repeating output, similar to the -d option in the watch command.

I want to see the changes of lsof and some other commands. That means, I want only the changed/new lines to be in red (instead of highlighted with a white background and highlighting all the following lines). Is there an elegant way to get it done with diff or any other command?

Example: A red line shows a new connection via SSH.

enter image description here

(I know, I could GREP for ESTABLISHED here, but not every command I want to watch gives me a keyword to search for. So I have to look for new/changed line in the output.)

Best Answer

You can use ANSI escape sequences. To set a color and style desired, there is a syntax \033[#m where # can be a valid set of semicolon separated numbers.

You can define colors such as

CLEAR="\033[0m"
GREEN="\033[0;32m"
BLUE="\033[0;34m"
PURPLE="\033[0;35m"
RED="\033[0;31m"
YELLOW="\033[1;33m"

And use them such as echo -e "${GREEN}Updated${CLEAR}"

Check here for more reference

Related Question