shBash
IntermediateLesson 6 of 15

Functions – Bash

Reusable building blocks with arguments, local variables and return values.

You define functions with name() { ... }. Inside, you access arguments with $1, $2, $@ – not those of the script. Variables are global by default; with local you make them local.

begruesse() {
  local name="$1"
  local gruss="${2:-Hello}"
  echo "$gruss, $name!"
}

begruesse "Ada"              # Hello, Ada!
begruesse "Linus" "Hi"       # Hi, Linus!

return delivers only an exit code (0–255), not values. You print text with echo and capture it via $(...). Functions with an exit code can be used directly as a condition.

quadrat() { echo $(( $1 * $1 )); }
ergebnis=$(quadrat 7)
echo "7 squared: $ergebnis"        # 49

ist_gerade() { (( $1 % 2 == 0 )); }     # the exit code of the calculation is returned
if ist_gerade 10; then echo "10 is even"; fi

fehler() { echo "ERROR: $*" >&2; exit 1; }     # helper function for aborting
[[ -f server.log ]] || fehler "server.log missing"
WarningWithout local, a function overwrites the caller's variables – a classic source of bugs. Also, $(quadrat 7) runs in a subshell: changes to global variables inside the function are lost.
TipDefine functions before their first use in the script. Group them at the top and call main "$@" at the end – this keeps scripts readable and testable.