Introducing UNIX and Linux |
Advanced shell programmingOverview |
FunctionsThe shell supports functions, which are a way of grouping commands together in a non-trivial manner without needing to write a new shell script. In complexity, functions lie between a straightforward pipe (or similar shell command) and a script. To create a function, you first of all choose a name for a
function, then enter that name, followed by
You must separate the braces from the function definition by blanks. To execute a function, simply type its name:
A function can only be used by the shell in which it has been
defined, and subshells or child processes cannot use it. A function
will use the environment of the current shell (so that you need not
Worked exampleWrite a function
You may be wondering why functions are needed - at first sight, they may appear an added complication to the shell, and duplicate the purpose of executable shell scripts. However, there are some operations which cannot be performed by a script. Consider writing a command to alter the value of a variable in the current shell. If it is implemented as a shell script, running the command involves creating a child process whose parent is the current shell. Any change in that variable's value will be done by the child process. However, there is no way that the child process can communicate the new value back to its parent, and the variable's value in the current shell thus remains unchanged. A function, however, would be executed by the current shell without sparking a child process, and could therefore be used successfully. Having defined one or more functions, you may wish to run a
command without looking up the function definitions. You may, for
instance, have a shell script that runs a command called
As a simple example, supposing you had called the function above
The effect of Another reason for using functions is efficiency. Executing a
function involves the shell in less work because it does not have
to create a new process. It can also be argued that functions are
easier to understand than shell scripts. One common function that
many users define, in order to speed up their sessions, is
If you wish to exit from a function before the end you should
use |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck