Delete a variable in awk

There is no operation to unset/delete a variable. The only time a variable becomes unset again is at the end of a function call when it's an unused function argument being used as a local variable:

$ cat tst.awk
function foo( arg ) {
    if ( (arg=="") && (arg==0) ) {
        print "arg is not set"
    }
    else {
        printf "before assignment: arg=<%s>\n",arg
    }
    arg = rand()
    printf "after assignment: arg=<%s>\n",arg
    print "----"
}
BEGIN {
    foo()
    foo()
}

$ awk -f tst.awk file
arg is not set
after assignment: arg=<0.237788>
----
arg is not set
after assignment: arg=<0.291066>
----

so if you want to perform some actions A then unset the variable X and then perform actions B, you could encapsulate A and/or B in functions using X as a local var.

Note though that the default value is zero or null, not zero or false, since its type is "numeric string".

You test for an unset variable by comparing it to both null and zero:

$ awk 'BEGIN{ if ((x=="") && (x==0)) print "y" }'
y
$ awk 'BEGIN{ x=0; if ((x=="") && (x==0)) print "y" }'
$ awk 'BEGIN{ x=""; if ((x=="") && (x==0)) print "y" }'

If you NEED to have a variable you delete then you can always use a single-element array:

$ awk 'BEGIN{ if ((x[1]=="") && (x[1]==0)) print "y" }'
y
$ awk 'BEGIN{ x[1]=""; if ((x[1]=="") && (x[1]==0)) print "y" }'
$ awk 'BEGIN{ x[1]=""; delete x; if ((x[1]=="") && (x[1]==0)) print "y" }'
y

but IMHO that obfuscates your code.

What would be the use case for unsetting a variable? What would you do with it that you can't do with var="" or var=0?


An unset variable expands to "" or 0, depending on the context in which it is being evaluated.

For this reason, I would say that it's a matter of preference and depends on the usage of the variable.

Given that we use a + 0 (or the slightly controversial +a) in the END block to coerce the potentially unset variable a to a numeric type, I guess you could argue that the natural "empty" value would be "".

I'm not sure that there's too much to read in to the cases that you've shown in the question, given the following:

$ awk 'BEGIN { if (!"") print  }'
5

("" is false, unsurprisingly)

$ awk 'BEGIN { if (b == "") print 5 }'
5

(unset variable evaluates equal to "", just the same as 0)

Tags:

Variables

Awk