Declare and call functions
A function gives a reusable name to a sequence of shell commands. Define it with greet() { printf "%s\n" hello; }, then call greet like any other command, without parentheses. The braces need separation from adjacent words, and the final command needs a newline or semicolon before the closing brace. Bash also accepts the function greet { ...; } form; the first form is preferable when aiming for POSIX shell syntax. Defining a function does not run its body. A normal call runs in the current shell, so assignments and directory changes may persist. A parenthesized body runs in a subshell environment instead. Use descriptive names to avoid accidentally shadowing existing commands; type shows how Bash resolves a name. Keep one clear responsibility per function. The current-shell behavior assumes an ordinary direct function call. Calling the same function in a command substitution or pipeline component can instead run it in a subshell environment.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Define once, call twice
greet() { printf '%s\n' hello}printf '%s\n' readygreetgreetExpected stdout:
readyhellohelloThe definition is silent; each call executes the body.
Bash keyword syntax
function report { printf '%s\n' report; }type -t reportreportExpected stdout:
functionreportThe keyword form is Bash-specific; type -t reports the command kind.
Current shell versus subshell
state=originalchange() { state=changed; }isolate() ( state=isolated; printf '%s\n' "$state" )changeisolateprintf '%s\n' "$state"Expected stdout:
isolatedchangedThe brace body changes the current shell; the parenthesized body does not.
Common mistakes
Do not call greet() as in other languages. Do not expect ordinary functions to isolate global assignments; use local variables or a deliberate subshell when appropriate.
Practice
Define a function that prints a two-line report header. Call it twice, then inspect its type. Predict the output before execution.
Next: Function arguments and return status