I have a script with a conditional statement and I want to find out how many times the then
clause is executed, across multiple runs of the same script.
eg:
if [condition]
then
Some code;
ACTIVATE COUNTER;
else
Some code;
RESET COUNTER;
fi
You need to store the count somewhere it will persist across multiple runs of the script, since variables are just in memory for that single run.
The easiest place is probably in a file.
The particular way you store it in a file depends on a few factors including how many times you're counting, and whether you expect concurrent runs. A simple robust way would be like this
This appends a line to a file every time it runs. (You might want to choose a better name or location for the file to reflect what it actually does in your program.)
This is pretty simple, and will be pretty robust if the script is interrupted or if you run several copies at the same time.
Then you can find the count with
wc -l ~/script-counter
You can reset the counter by just emptying the file, with
(
:
is a shell builtin command that does nothing, so redirecting it to the file empties the file.)