How to write a Bash function

Write Bash functions with parameters, local variables, and return values. Covers the difference between return (exit status) and echo (data output).

Tldr

Define a function with `name() { ...; }`, access its arguments as $1, $2, "$@" just like a script, and always declare internal variables with `local` to avoid leaking into the caller's scope. Use `return` only for a numeric exit status (0-255); to return actual data, `echo` it and capture with command substitution.

Intro

Bash functions behave more like mini-scripts than functions in other languages — they share the calling shell's environment unless you scope variables explicitly, and "return values" mean exit status, not arbitrary data.

Steps

Name

Define a function and access its arguments

Text

Function arguments are positional parameters just like a script's: $1, $2, $#, and "$@" all work the same way inside a function body.

Name

Use local for internal variables

Text

Without local, a variable assigned inside a function is global and can silently overwrite a variable of the same name in the caller.

Name

Return a numeric exit status

Text

return sets the function's exit status (0-255, checked with $? or directly in an if), similar to how a script exits. It does not carry back arbitrary data.

Name

Return data with echo and command substitution

Text

To get a computed value (a string or number) back to the caller, print it with echo and capture the output with $(...).

Name

Pass an array or return multiple values with nameref

Text

For Bash 4.3+, declare -n creates a nameref parameter, letting a function modify a variable in the caller's scope directly by name — useful for "returning" arrays or multiple values.

Faq

Q

Can a Bash function return a string directly like other languages?

A

No — `return` only accepts an integer 0-255 as an exit status. To hand back string or numeric data, print it with echo/printf and capture it in the caller with command substitution, e.g. `result=$(myfunc)`.

Q

Why did a variable inside my function change a variable outside it?

A

Bash function variables are global by default unless declared with `local`. Always use `local varname` for anything that should not leak into or clobber the caller's scope.

Q

Do functions need to be defined before they are called?

A

Yes — Bash reads a script top to bottom, so a function must appear (be defined) earlier in the file than the point where it is called, or the call fails with "command not found".