Functions


Functions are predefined groups of statements that can be called with a single command. They can almost be thought of as mini-programs inside other programs. Using functions in your shell programs can make your life a lot easier for two reasons. First, if you need to perform a complex operation in multiple places in your program, you can simply type the name of the function rather than having to retype all the code each time you need to perform the operation. Secondly, if you later decide you need to make the operation work differently, you only have to change the function rather than go through the code and change it every place it is used. The example in Listing 10.20 demonstrates how a function is created; it shows a simple function that cleans up temp files after a shell program exits. It then shows how to call the function.

Listing 10.20. Using a Function

1.  #!/bin/sh 2.  on_exit() { 3.      rm -rf /tmp/myprogram.* 4.      mv logfile logfile.old 5.      mail foo@bar.com < report.txt 6.  } 7.  trap on_exit 0 1 2 3 15

This function is given a name (on_exit), followed by parentheses and a left bracket. Everything between the two brackets is the body of the function. The function can then be called as if it were a program, simply by using its name. As stated previously, functions can almost be thought of as mini-programs inside other programs. Any time you type the name of this function, the statements between its brackets will be performed.

There is one important difference between calling a function and calling another program, though. The function is run in the current shell, whereas a separate program starts in a subshell. This means that a function can modify the variables and environment variables in the program that calls it. But a separate program called from inside a shell program cannot modify any of the variables or environment variables in the calling program.




FreeBSD 6 Unleashed
FreeBSD 6 Unleashed
ISBN: 0672328755
EAN: 2147483647
Year: 2006
Pages: 355
Authors: Brian Tiemann

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