Gabriel Staples
Gabriel Staples

Reputation: 53065

How can I display the run count as part of the `watch` output in a terminal?

I'd like to see a run counter at the top of my watch output.

Ex: this command should print a count value which increments every 2 seconds, in addition to the output of my main command, which, in this case is just echo "hello" for the purposes of this demonstration:

export COUNT=0 && watch -n 2 'export COUNT=$((COUNT+1)); echo "Count = $COUNT" \
&& echo "hello"'

But, all it outputs is this, with the count always being 1 and never changing:

Count = 1
hello

How can I get this Count variable to increment every 2 seconds when watch runs the command?

Upvotes: 1

Views: 878

Answers (1)

Gabriel Staples
Gabriel Staples

Reputation: 53065

Thanks @Inian for pointing this out in the comments. I've consulted the cross-site duplicate, slightly modified it, and come up with this:

count=0; while sleep 2 ; do clear; echo "$((count++))"; echo "hello" ; done

Replace echo "hello" with the real command you want to run once every sleep n second now, and it works perfectly.

There's no need to use watch at all, and, as a matter of fact, no way to use watch in this way either unless you write the variable to a file rather than to RAM, which I'd like to avoid since that's unnecessary wear and tear write/erase cycles on a solid state drive (SSD).


Now I can run this command to repeatedly build my asciidoctor document so I can view it in a webpage, hitting only F5 each time I make and save a change to view the updated HTML page.

count=0; while sleep 2 ; do clear; echo "$((count++))"; \
asciidoctor -D temp README.adoc ; done

Sample output:

96
asciidoctor: ERROR: README.adoc: line 6: level 0 sections can only be used when doctype is book

Final answer:

And, here's a slightly better version which prints count = 2 instead of just 2, and which also runs first and then sleeps, rather than sleeping first and then running:

count=1; while true ; do clear; echo "count = $((count++))"; \
asciidoctor -D temp README.adoc; sleep 2 ; done

...but, it looks like it's not just updating the file if it's changed, it's rewriting constantly, wearing down my disk anyway. So, I'd need to write a script and only run this if the source file has changed. Oh well...for the purposes of my original question, this answer is done.

Upvotes: 2

Related Questions