Search code examples
awkposixconditional-operator

Set variable if it is unset in awk


I want to set the variable foo to bar if foo was previously undefined. Currently I'm using

foo = foo ? foo : bar

But I have the feeling that there is a smarter way to do this in POSIX awk. For example in POSIX Shell I could write

${foo:-bar}

Solution

  • Robustly in any awk assuming foo is a scalar variable and cannot be an array:

    foo = ( (foo == 0) && (foo == "") ? bar : foo )
    

    An uninitialized scalar variable has the value zero-or-null as no "type" attribute (string or numeric) has been associated with it yet and so comparing a variable to both zero and null succeeds if it isn't set and fails otherwise.