Functions in Bash

From the Bash Scripting cheat sheet · Functions · verified Jul 2026

Functions

Define, pass arguments, and return results.

bash
# Quick Reference
greet() {
    local name="$1"
    echo "Hello, $name"
}
greet "Sam"
result="$(greet "Sam")"   # capture the echoed output
💡 Function args are $1, $2, ... just like script args - not named parameters.
⚡ return sets an exit status (0-255) for success/failure; echo + $(...) returns data.
📌 Declare internal variables local so functions do not clobber global state.
🟢 ${1:-default} gives a parameter a fallback when the caller omits it.
functions
Back to the full Bash Scripting cheat sheet