function
Define and name reusable code blocks
TLDR
Define a function with the specified name
Run a function named func_name
Display help
SYNOPSIS
function function_name { command_list ; }
or function_name() { command_list ; }
DESCRIPTION
The function
command in Linux, often used implicitly when defining functions, allows you to create reusable blocks of code within your shell environment. It's a mechanism for grouping commands together under a single name, which can then be invoked like any other command. Functions can accept arguments, perform operations, and return values, making them powerful tools for scripting and automation.
While the function
keyword is often optional in many shells (like bash and zsh), explicitly using it provides clarity and can improve script portability to shells that require it. Functions help modularize your code, making it easier to read, maintain, and debug. They promote code reuse, preventing the need to repeatedly write the same sequence of commands. By encapsulating complex operations into functions, you can simplify your scripts and make them more manageable. They also contribute to creating more robust and reusable shell scripts. Within a function you can access arguments using $1, $2,... and so on, similar to script arguments. Special variables such as $@ and $* contain all the arguments, and $# holds the number of arguments.
CAVEATS
The function
keyword is often optional in bash and zsh, but is required in some older shells or when strict POSIX compliance is needed. Functions defined in a shell session are typically only available during that session, unless exported using `export -f` to make them available to subprocesses. Be aware of variable scoping; variables defined within a function are local by default, unless declared global using the `declare -g` command.
SCOPE
Functions defined in a script have a scope local to the script unless sourced (using the .
or source
command). Sourcing a script makes the functions defined within it available in the current shell environment.
RETURN VALUES
Functions can return an exit status using the return
command. This value can be accessed using the $?
variable after the function is executed. They can also return values via standard output which can be captured with command substitution.
EXAMPLES
Example 1: Simple function
my_function() { echo "Hello, world!"; }
my_function
Example 2: Function with argumentsgreet() { echo "Hello, $1!"; }
greet John
Example 3: Function with return valueadd() { return $(( $1 + $2 )); }
add 5 3; echo $?