Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Bash and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic Bash:

apply() {            # takes a FUNCTION NAME as first arg
  local fn=$1; shift
  "$fn" "$@"         # call it indirectly
}
shout() { echo "${1^^}"; }
apply shout hello    # -> HELLO
# build a callback table
declare -A handler=([add]=do_add [del]=do_del)
"${handler[add]:-do_default}" 42

Bash note: Bash passes functions only by *name* (there are no function values), so higher-order code stores names in variables/arrays and invokes them via "$fn" — with the usual quoting risks if the name is untrusted.

Try it yourself

Exercise: In Bash, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in Bash. Mark this lesson complete and continue to the next one.