100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

User-Defined Functions in AWK

Learn to define reusable functions in AWK, understand its unusual parameter-passing rules — scalars by value, arrays by reference — and use the extra-parameter trick for local variables.

Control Flow & FunctionsIntermediate10 min readJul 10, 2026
Analogies

Defining Your Own Functions

AWK lets you define reusable functions with the function keyword: function name(params) { ... }. Functions can appear anywhere at the top level of the program — before or after the rules that call them — and they may take parameters, use return to yield a value, and call other functions or themselves recursively. This lets you factor repeated logic out of your pattern-action rules, turning sprawling one-liners into readable, testable scripts. A function without a return statement (or with a bare return) yields the empty string / zero.

🏏

Cricket analogy: A user-defined function is like a set bowling plan you can call for any batter: bowl_yorker() — define the delivery once, then reuse it over after over instead of re-explaining it each ball.

Parameter Passing: Scalars by Value, Arrays by Reference

AWK's most surprising rule is that scalar arguments (numbers and strings) are passed by value, while array arguments are passed by reference. This means a function can modify the contents of an array passed to it and the caller sees the changes, but assigning to a scalar parameter never affects the caller's variable. This asymmetry is deliberate and useful: you commonly pass an array into a function so it can be filled or transformed in place — for example a split-style helper that populates a result array the caller then reads.

🏏

Cricket analogy: Passing a scalar by value is like telling a batter the target score verbally — he can't change the real total; passing an array by reference is like handing over the actual scorebook, where any runs he writes stick.

Local Variables via Extra Parameters

AWK has no dedicated local keyword. The idiomatic way to get local variables is to declare extra parameters in the function header beyond those the caller supplies — these are automatically initialized to empty/uninitialized and act as locals. By convention they are separated from real parameters by extra whitespace, e.g. function total(arr, i, sum), where i and sum are locals. Forgetting this trick is a classic bug source: a loop variable like i used without being a parameter becomes global and can clobber a caller's i.

🏏

Cricket analogy: Extra-parameter locals are like a bowler's private scratchpad for field placements — kept to himself; forgetting to make i local is like shouting your plan so the whole ground (global scope) overhears and gets confused.

awk
# functions can appear anywhere; recursion is allowed
function max(a, b) {
    return (a > b) ? a : b
}

# extra params i and sum are locals (note the wide gap after the real arg)
function sumfields(   i, sum) {
    sum = 0
    for (i = 1; i <= NF; i++) sum += $i
    return sum
}

# array passed by reference: the function fills the caller's array
function tally(line, counts,    n, i, words) {
    n = split(line, words, " ")
    for (i = 1; i <= n; i++) counts[words[i]]++
    return n
}

{
    print "row", NR, "sum:", sumfields(), "biggest field vs 100:", max($1, 100)
    tally($0, freq)          # freq is populated in place by reference
}
END {
    for (w in freq) print w, freq[w]
}

There must be no space between a user-defined function's name and its opening parenthesis at the call site: write max(a, b), not max (a, b). AWK allows a space for built-in functions but not for user-defined ones, and the mistake produces a confusing parse error.

Any variable used inside a function that is not a parameter is global. A loop counter i left undeclared will silently share and overwrite the caller's i, causing subtle bugs that only appear when the caller also uses i. Always list scratch variables as trailing extra parameters.

  • Define functions with function name(params) { ... }; they may appear anywhere at top level.
  • Scalars are passed by value; arrays are passed by reference and can be modified in place.
  • return yields a value; a function with no return gives the empty string / zero.
  • AWK has no local keyword — declare extra trailing parameters to create local variables.
  • Undeclared variables inside functions are global and can clobber the caller's variables.
  • No space is allowed between a user function's name and its ( at the call site.
  • Functions may be recursive and may call other user-defined functions.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#AWKStudyNotes#UserDefinedFunctionsInAWK#User#Defined#Functions#AWK#StudyNotes#SkillVeris#ExamPrep