Functions & Arguments

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Bash

Functions & Arguments

Intermediate ⭐ 80 XP ⏱ 16 min #bash#functions

Structure scripts with reusable functions, parameters, and return values.

📖Theory

Functions group related logic so scripts stay readable and DRY. Inside a function, arguments are $1, $2, $@ — just like a script. A function communicates back in two ways:

  • Exit status via return N (0–255) — for success/failure
  • Output via echo captured with result=$(myfunc) — for actual data

Use local to scope variables inside a function so they don’t leak into the global namespace and cause spooky bugs.

🌍Real-World Example
#!/usr/bin/env bash

log() {                          # a helper used everywhere
  local level="$1"; shift
  echo "[$level] $*"
}

add() {
  local sum=$(( $1 + $2 ))
  echo "$sum"                     # output, captured by caller
}

is_even() {
  (( $1 % 2 == 0 )) && return 0 || return 1
}

log INFO "starting"
total=$(add 3 4)                  # total = 7
if is_even "$total"; then log INFO "even"; else log INFO "odd"; fi
✍️Hands-On Exercise
  1. Write a greet function that takes a name and prints a greeting.
  2. Write a function that returns success/failure based on whether a file exists.
  3. Use local to prove a variable doesn’t leak outside the function.
  4. Capture a function’s echoed result into a variable and use it.
🧾Cheat Sheet
ItemSyntax
Definename() { … }
Arguments$1 $2 $@ $*
Local variablelocal x=…
Return statusreturn N (0–255)
Shift argsshift
Capture outputr=$(func args)
💬Common Interview Questions
How does a Bash function return a value?

Two channels: return sets an exit status (0–255) for success/failure, while data is returned by echoing it and capturing with $(func).

Why use local in functions?

It scopes a variable to the function so it doesn’t overwrite or leak into global variables — preventing subtle bugs in larger scripts.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type