7.3.6.1. Functions

Functions can be considered as small scripts within a larger script. They are usefull if some actions have to be done several time. These actions can be collected in a function.

A function is defined as:

function_name () {
    <commands>
}

Another, completely equivalent way, to specify a function, is by using:

function function_name {
    <commands>
}

The function has to be defined before use. After that, a call to function_name will execute all <commands>.

Note that, contrary to other program languages, the function definition, does not include the name of the parameters that will be used when calling the function. The parentheses in the first definition are always empty.

Here is an example:

alert () {
    echo "An error occured!"
}

In the shell script, now alert can be used, and will print “An error occured!” to stdout.

Maybe the alert function should print an error to stderr. How should this be done?