The reserved word function (see section “Compound commands”) is used to define POSIX shell functions. Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are executed like commands, with arguments passed as positional parameters (see section “Execution”).
Functions execute in the same process as the caller and share all open files and the present working directory with the caller.
Traps caught by the caller are reset to their default action inside the function. A trap condition that is not caught or ignored by the function causes the function to terminate; the condition is then passed on to the caller. A trap on EXIT set inside a function is executed after completion of the function in the environment of the caller.
Variables are usually shared between the calling program and the function. However, the built-in typeset command can be used within a function to define local variables whose scope includes the current function and all functions it calls.
The built-in return command is used to return from function calls. Errors that occur within functions return control to the caller.
Function identifiers or names can be listed with the -f or +f option of the built-in typeset command. The text of functions may also be listed with the -f option. Functions can be undefined with the -f option of the built-in unset command.
Functions are usually not accessible when the POSIX shell executes a shell script.
The -xf option of the typeset command allows a function to be marked for export. These functions can then be used in scripts that are executed without a separate invocation of the POSIX shell. Functions that need to be defined across separate invocations of the shell should be specified in the ENV file with the -xf option of typeset.
Example
The following function named lh lists the top two levels of the directory hierarchy in which you are located or which you specify as an argument. Regular files are ignored as arguments.
function lh { for i in ${*:-.} do if [[ -d $i ]] then print $i: cd $i ls -CF $( ls ) cd - >/dev/null fi done }
The for loop processes each of the specified arguments in succession. If you have not specified an argument, $* is set to the current directory (.).
If a directory is present, its name and contents are listed as follows: cd $i switches to the directory to be listed; $( ls ) is replaced by the content of the directory $i, and ls -CF directory_list lists the files, followed by the contents of the directories, with flags to indicate executables and directories. The subsequent cd command silently returns to the initial directory (before the first cd $i).