Function Definition

A function definition takes the following form,

function-name() compound-command [io-redirect ...]

Typically, the compound-command is a brace group, and the function definition is written as,

func() {
   ...
} [ redirections ]

This simulates a familiar C-style function syntax. However, technically, any type of compound command can be used as the function body, as we will demonstrate in a moment.

When a function is defined, none of the commands in the compound-command are executed, no expansions are performed on the compound-command or optional redirections, and none of the optional redirections are carried out. All of these operations are carried out during execution of the function, not in its definition. Whenever the function name is specified as the name of a simple command, the function’s compound-command is executed with the optional redirections performed at that point.

Additionally, there is no concept of variable scope–all variables are part of a global shell environment. A function executes in the current shell environment and can modify and inspect variables.

$ f() { echo $((++x)); }
$ x=0
$ f
1
$ f
2
$ f
3
$ echo $x
4

Remember, the compound-command does not need to be brace group. A subshell might be used instead, if modifying the external environment is not desired:

$ f() ( echo $((++x)); )
$ x=0
$ f
1
$ f
1
$ x=2
$ f
3
$ f
3
$ echo $x
2

Function Parameters

The operands to the simple command temporarily become the positional parameters during execution of the function; the special parameters #, @, and * are affected by this change. When the function completes, the values of the positional parameters are restored to their values from before the function was executed.

Example

$ f() { echo Arguments are: "$@"; }
$ f alpha beta
Arguments are: alpha beta
$ f gamma delta
Arguments are: gamma delta

Explicit Return

Execution of a function completes with the execution of its compound-command; however, the return [n] builtin may be used to return explicitly from a function, with a specified value. If n is not specified, the return value is the exit status of the last command executed.

Exit Status

The exit status of a function definition is 0 if the declaration is successful; otherwise a non-zero error value is set.

The exit status of a function invocation is the exit status of the last command executed by the function, or the return value as described above.