View and vote on the article here: Shell Programming Series(XVIII)
Shell Programming Series(XVIII)| Category | | | Summary | Functions
Functions are basically groups of statements that can be called with a single command. They can almost be thought of as "mini-programs inside programs." |
| | Body | Using functions in your shell programs can make your life a lot easier - for two reasons. First of all, if you need to perform the operation in multiple places in your program, you can simply type the name of the function rather than having to retye all the code each time you need to perform the operation. Second, 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 following shows a simple example of a function that cleans up temp files, and so on, after a shell program exit. It then shows how to call the function:
#!/bin/sh
on_exit() {
rm -rf /tmp/myprogram.*
mv logfile logfile.old
mail ismail@mail.cyberarmy.com < report.txt
}
trap on_exit 0 1 2 3 15
The previous sample shows how a function is created. It is given a name, followed by parentheses and a left bracket. Everything between the two brackets is the body of a 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 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.
|
|
This article was imported from zZine. (original author: ismail)
There are no replies to this post yet.
|