Keep track of the times a script is being run

The fact: you need to know how many times a given script has been run lately. This task is quite trivial if you keep the number in a given temporary file.

What I am going to show you instead, is how to store the number just directly in the same script.
Oh well, not that this is too hard to do but it’s a nice trick that may give you an idea of how self-extracting script do work (e.g. nvidia official drivers and common linux games are shipped with this type of container).

Let’s go to the core of the problem: in order to distinguish the code from the data, we need to put the first on top of the file and then tell the shell interpreter when it has to stop reading. How we can do this? With exit, of course

Now, the problem is reduced to a read-a-file-and-increment-a-number which is quite easy if you have familiarity with sed/awk et similia:

awk '/^[0-9]+$/{$0++} 1' $0

The above command will search in $0 (which is the current script in bash) for a line containing only a number (/^[0-9]+$/) and replaces it with its value increment by 1 unit ($0 in awk is the current line). The one (1) before the single quote, is there just to tell awk to print the current line.
With a temporary file we can write the changes in a safe place and then move it over the current script:

#!/bin/bash

tmpfile=$(mktemp)

awk '/^[0-9]+$/{$0++} 1' $0 >$tmpfile

mv $tmpfile $0

exit

0

Every time you run the above script, the number at the bottom line will be increased by one unit.

Hope this helps!

None
A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".