LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

function

shell function definition keyword

TLDR

Define a function
$ function greet() { echo "Hello $1"; }
copy
Call the function
$ greet [World]
copy
List defined functions
$ declare -F
copy
Show function definition
$ declare -f [function_name]
copy
Unset function
$ unset -f [function_name]
copy

SYNOPSIS

function name() { commands; }

DESCRIPTION

function is a shell keyword for defining reusable command groups. Functions encapsulate commands, accept parameters, and can return exit status values.Functions enable code reuse, modularity, and cleaner scripts. They have local scope for variables with the `local` keyword. Parameters are accessed through positional variables ($1, $2, etc.).In bash, both `function name() { ...; }` and `name() { ...; }` syntax define functions. The POSIX-portable form omits the `function` keyword. In ksh and zsh, the `function` keyword is also supported.

PARAMETERS

NAME

Function name.
COMMANDS
Function body commands.
$1, $2, etc.
Positional parameters.
$@
All parameters.
return N
Exit function with status.
local VAR
Declare local variable.

CAVEATS

Functions must be defined before use. `return` only sets exit status (0-255), not output values — use command substitution to capture output. Variable scope requires explicit `local` declarations; without it, variables are global.

SEE ALSO

bash(1), declare(1), local(1), unset(1)

Copied to clipboard
Kai