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.
# 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.
returnyields a value; a function with no return gives the empty string / zero.- AWK has no
localkeyword — 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
1. How are scalar and array arguments passed to AWK functions?
2. How do you create local variables inside an AWK function?
3. What happens to a non-parameter variable used inside a function?
4. What does a user-defined function return if it has no `return` statement?
5. Which call syntax is correct for a user-defined function `sq`?
Was this page helpful?
You May Also Like
Arrays in AWK
Understand AWK's associative arrays — string-keyed, dynamically growing collections used for counting, grouping, and lookups — plus multi-dimensional emulation, membership tests, and deletion.
Loops in AWK
Master AWK's iteration constructs — while, do-while, for, and the array-oriented for-in loop — along with break, continue, and next for controlling flow through records and data.
String Functions in AWK
Explore AWK's built-in string functions — length, substr, index, split, sub, gsub, match, sprintf, and case conversion — for extracting, searching, and transforming text.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics