0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

Designing Functions with Local Scope and Return Codes

Write functions that use local variables, exit statuses, and printf-based return values instead of fragile globals.

Why Function Scope Matters

In Bash, variables are global by default. A variable set inside a function leaks out into the caller's scope unless you explicitly declare it local. This is a common source of subtle bugs in shell scripts.

  • Functions without local can silently overwrite caller variables.
  • local variables are destroyed when the function returns.
  • Clean scope boundaries make functions reusable and testable in isolation.

This lesson teaches you to write functions that are self-contained: they use local variables, communicate results through exit codes and printf, and never rely on implicit global state.

The Global Leak Problem

Here is a concrete example of a global variable leak. The function set_name sets a variable called result, which quietly overwrites the caller's own result variable.

Run this script and observe the unexpected output — the caller's result is gone after the function call.

#!/usr/bin/env bash

set_name() {
    result="Alice"   # No 'local' — this is GLOBAL
}

result="important data"
echo "Before: $result"

set_name

echo "After:  $result"   # Prints 'Alice', not 'important data'

All lessons in this course

  1. Designing Functions with Local Scope and Return Codes
  2. Building and Sourcing Reusable Bash Libraries
  3. Parsing Flags and Arguments with getopts
  4. Passing Arrays and Associative Maps Between Functions
← Back to Linux Command Line & Bash Scripting Mastery