A Bash function groups commands under a name. Calling the function runs its body with its own positional arguments.

Program

Play the script to watch the call pass Ada into the function body.

functions.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

greet() {
  local name="$1"
  echo "Hello, $name"
}

greet "Ada"
  1. greet ← defined

    3greet() {4  local name="$1"
    values this stepdefinedgreet
  2. call ← greet Ada

    8greet "Ada"
    values this stepgreet Adacall
  3. name ← Ada

    3greet() {4  local name="$1"5  echo "Hello, $name"
    values this stepAdanameAda$1
  4. echo "Hello, $name"

    4  local name="$1"5  echo "Hello, $name"6}
    outputHello, Ada
    values this stepAdaname

Follow the Call

  1. greet() is defined before it is called.
  2. The call is greet "Ada".
  3. Inside the function, $1 is Ada.
  4. local name becomes Ada.
  5. The function prints Hello, Ada. | place | value | | --- | --- | | call argument | Ada | | function $1 | Ada | | local name | Ada | | stdout | Hello, Ada |
function A function names a reusable group of shell commands.
local `local` keeps a variable scoped to the current function call.

Exercise: functions.sh

Reproduce Hello, Ada, then identify how the call argument becomes the function's local name.