2

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
2

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

if CONDITION
then
    echo run >> ~/script-counter
fi

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

: > ~/script-counter

(: is a shell builtin command that does nothing, so redirecting it to the file empties the file.)

  • Hey thanks nice idea but how to reset the counter? any idea – Eka May 22 '15 at 5:09
  • 3
    @eka: just overwrite the file: : > ~/script-counter – Jeremy Kerr May 22 '15 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.