The following code results in an infinite loop because awk doesn't support local variable in { … } scope.

#! /usr/bin/gawk -f

function myfunction() {
    for (i = 5; i < 8; i++){
        print "in myfunction(), i="i

    for (i = 0; i < 10; i++) {
        print i;

There are two ways to deal with this problem :

  1. Declare loop variable i as arguments, e.g. myfunction( i).

Note the extra space before i is a coding convention to indicate that i is a local variable, not an argument.

  1. Use naming convention to prevent 'collision', e.g. _module_begin_loop, _module_myfunction_loop.

I found that the first solution is quite tricky for a loop variable, since myfunction() is not necessarily called in a loop. As for the second, it can make a long name which will decrease readability.

closed as primarily opinion-based by G-Man Says 'Reinstate Monica', steve, shirish, Kiwy, Kusalananda May 15 '18 at 10:16

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    On a side note, sometimes it is possible, and desirable, to break a problem into different phases and do each in a separate awk program, piping the intermediate data between them. You might compare this with how a compiler might do a cpp lexical pass, then compile to an RTL language, then assembler, then binary, in 4 separate programs hidden behing the command cc. – meuh May 13 '18 at 9:14

I found an answer when I was preparing this question. Other answers are welcome.

In relatively big awk project, like translate-shell the first solution is used :

function parseList(returnAST, tokens,
                   i, j, key, p, stack, token) {

parameters after #### are local.

awk allows to call function with fewer parameters, e.g. parseList(ast, tokens) or parseList(ast, tokens, lb, rb, sep). Hence, only the signature is complicated.

Not the answer you're looking for? Browse other questions tagged or ask your own question.