Next: , Previous: , Up: General Introduction  

2 Quick Start

Here’s pm-gawk in action at the bash shell prompt (‘$’):

        $ truncate -s 4096000 heap.pma
        $ export GAWK_PERSIST_FILE=heap.pma
        $ gawk 'BEGIN{myvar = 47}'
        $ gawk 'BEGIN{myvar += 7; print myvar}'

First, truncate creates an empty (all-zero-bytes) heap file where pm-gawk will store script variables; its size is a multiple of the system page size (4 KiB). Next, export sets an environment variable that enables pm-gawk to find the heap file; if gawk does not see this envar, persistence is not activated. The third command runs a one-line AWK script that initializes variable myvar, which will reside in the heap file and thereby outlive the interpreter process that initialized it. Finally, the fourth command invokes pm-gawk on a different one-line script that increments and prints myvar. The output shows that pm-gawk has indeed “remembered” myvar across executions of unrelated scripts. (If the gawk executable in your search $PATH lacks the persistence feature, the output in the above example will be ‘7’ instead of ‘54’. See Installation.) To disable persistence until you want it again, prevent gawk from finding the heap file via unset GAWK_PERSIST_FILE. To permanently “forget” script variables, delete the heap file.

Toggling persistence by export-ing and unset-ing “ambient” envars requires care: Forgetting to unset when you no longer want persistence can cause confusing bugs. Fortunately, bash allows you to pass envars more deliberately, on a per-command basis:

        $ rm heap.pma                    # start fresh
        $ unset GAWK_PERSIST_FILE        # eliminate ambient envar
        $ truncate -s 4096000 heap.pma   # create new heap file

        $ GAWK_PERSIST_FILE=heap.pma gawk 'BEGIN{myvar = 47}'
        $ gawk 'BEGIN{myvar += 7; print myvar}'
        $ GAWK_PERSIST_FILE=heap.pma gawk 'BEGIN{myvar += 7; print myvar}'

The first gawk invocation sees the special envar prepended on the command line, so it activates pm-gawk. The second gawk invocation, however, does not see the envar and therefore does not access the script variable stored in the heap file. The third gawk invocation does see the special envar and therefore uses the script variable from the heap file.

While sometimes less error prone than ambient envars, per-command envar passing as shown above is verbose and shouty. A shell alias saves keystrokes and reduces visual clutter:

        $ alias pm='GAWK_PERSIST_FILE=heap.pma'
        $ pm gawk 'BEGIN{print ++myvar}'
        $ pm gawk 'BEGIN{print ++myvar}'

Next: Examples, Previous: Introduction, Up: General Introduction