7

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.)

2
  • That's what watch is for. But I suppose you could lsof > /tmp/thing && lsof > /tmp/thing2 && diff /tmp/thing /tmp/thing2
    – coteyr
    Commented Feb 5, 2016 at 23:19
  • Have a look at multitail as well, which is a full-screen log viewer. You can monitor the output of processes or pipelines as well as disk files, and set up filtering and highlighting rules based on lines that match a pattern. It doesn't have anything like watch -d to my knowledge, but worth adding to the toolbox regardless. :)
    – Kevin E
    Commented Sep 29, 2021 at 19:15

2 Answers 2

2

Finally I found a way to achieve it. I wanted to avoid file operations (tmpfs and such) for performance and latency reasons. The trick is to tell dwdiff or wdiff in its two arguments what the output of a command is and was within the same iteration. Process substitution was my helping hand:

while true; do p1=$p2; p2=$(clear; iotop -ob -n1); 
    dwdiff -y "\010" -1 -c <(echo "$p1") <(echo "$p2"); sleep 1; done

The -y "\010" removes the space before the changed word to keep the columns nicely aligned. $p1 and $p2 are used to keep the scope for the process substitutions <(...). Providing the output in the substitutions directly didn't work for me. I got this hint from this post.

Maybe there's a much simpler solution and I just got too complicated after all. Feel free to post it!

1
  • wondering how to make the highlighted colors stay, any suggestions? Commented Jan 31, 2018 at 13:03
1

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

1
  • Thanks. I already tried this. To clarify my needs I just updated my post with a screenshot.
    – awado
    Commented Feb 6, 2016 at 12:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .