4.4. Functions

 < Day Day Up > 

A shell function is a grouping of commands within a shell script. Shell functions let you modularize your program by dividing it up into separate tasks. This way the code for each task need not be repeated every time you need to perform the task. The POSIX shell syntax for defining a function follows the Bourne shell:

     name (  ) {         function body's code come here     }

Functions are invoked just as are regular shell built-in commands or external commands. The command line parameters $1, $2, and so on receive the function's arguments, temporarily hiding the global values of $1, etc. For example:

     # fatal --- print an error message and die:     fatal (  ) {         echo "$0: fatal error:" "$@" >&2     # messages to standard error         exit 1     }     ...     if [ $# = 0 ]    # not enough arguments     then         fatal not enough arguments     fi

A function may use the return command to return an exit value to the calling shell program. Be careful not to use exit from within a function unless you really wish to terminate the entire program.

Bash and the Korn shell allow you to define functions using an additional keyword, function, as follows:

     function fatal {         echo "$0: fatal error:" "$@" >&2     # messages to standard error         exit 1     }

When working with the different shells and defining functions, there are semantic differences that should be kept in mind:

  • In Bash, all functions share traps with the "parent" shell (except the DEBUG trap, if function tracing has been turned on). With the errtrace option enabled (either set -E or set -o errtrace), functions also inherit the ERR trap. If function tracing has been enabled, functions inherit the RETURN trap. Functions may have local variables, and they may be recursive. The syntax used to define a function is irrelevant.

  • In ksh88, all functions have their own traps and local variables, and may be recursive.

  • In ksh93, name ( ) functions share traps with the "parent" shell and may not be recursive.

  • In ksh93, function functions have their own traps and local variables, and may be recursive. Using the . command with a function function gives it POSIX shell semantics (i.e., shared traps and variables).

     < Day Day Up > 


    Unix in a Nutshell
    Unix in a Nutshell, Fourth Edition
    ISBN: 0596100299
    EAN: 2147483647
    Year: 2005
    Pages: 201

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net