DomainsFeatured DomainsFeatured - 1 year ago 76
Linux Question

How To Delete A File Every X Times A Script Is Run - Manage A Log File From Inside A Script?

I would normally just schedule this as a cron job or script, however, I would like to delete a log file (it's constantly appended to every time a script runs) only after 50 times.

Needed Inside The Script:

The thing is, since the script does not run consistently, it has be to be implemented within the script itself. Please note: for various reasons, I need this inside the script.

What I Was Trying:

I was thinking of setting a variable to increment, outputting it to a file and then having the script read that file every time. Then, if that value is greater than X, remove the file. That portion of the code would be a


Anyone know an easy, better way to do this? Your positive input is highly appreciated.

Answer Source

Since the Gnu awk v.4.1 the inplace edit has been available (see awk save modifications inplace) so, you could store the counter to your awk script variable and use the awk script to edit itself and decrement the counter varible like this:

$ cat program.awk
    this=5                                  # the counter variable
/this=[0-9]+/ {                             # if counter (this=5) matches
    if(this==0)                             # if counter is down to 0...
        ;                                   # ... do what you need to do
    split($0,a,"=")                         # split "this=5" by the "="
    sub(/=[0-9]+$/,"=" (a[2]==0?5:a[2]-1))  # decrement it or if 0 set to 5 again
1                                           # print

Run it:

$ awk -i inplace -f program.awk program.awk
$ head -3 program.awk
    this=4                                  # the counter variable

Basically you run program.awk that changes one record in program.awk inplace and once counter hits 0, the if gets executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download