Bash 5 reference · Shell Builtins and Syntax
function (Bash builtin)
Group commands into a named function that takes arguments like a script ($1, $@) and returns an exit status.
Bash 5
Syntax
name() { COMMANDS; }
Parameters
| Parameter | Description |
|---|---|
$1, $2, $@, $# |
Arguments, all arguments, argument count. |
local |
Variables scoped to the function. |
return N |
Set the exit status (0-255). |
Examples
greet() { local who="${1:-world}"; echo "hello $who"; }
greet
greet Ana
Output
hello world hello Ana
Run this on your computer — see “Get Started” for setup.
is_even() { (( $1 % 2 == 0 )); }
for n in 3 4; do is_even "$n" && echo "$n even" || echo "$n odd"; done
Output
3 odd 4 even
Run this on your computer — see “Get Started” for setup.
Related
local· Declare variables that exist only inside the current function, so they don't overwrite globals with the same name.- Bash Functions · tutorial