LinuxCommandLibrary

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.
In bash, both "function name()" and "name()" syntax define functions.

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 provides exit status, not values. Variable scope requires explicit local declarations.

HISTORY

Functions were added to the Bourne shell and expanded in bash and ksh. They're now a fundamental shell scripting construct supported by all POSIX shells.

SEE ALSO

bash(1), return(1), local(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard

> TERMINAL_GEAR

Curated for the Linux community