< Day Day Up > |
14.7. FunctionsFunctions were introduced to the Bourne shell in AT&T's UNIX SystemVR2 and have been enhanced in the Bourne Again shell. A function is a name for a command or group of commands. Functions are used to modularize your program and make it more efficient. They are executed in context of the current shell. In other words, a child process is not spawned as it is when running an executable program such as ls. You may even store functions in another file and load them into your script when you are ready to use them. Here is a review of some of the important rules about using functions.
FORMAT function function_name { commands ; commands; } Example 14.55.
function dir { echo "Directories: ";ls -l|awk '/^d/ {print $NF}'; }
EXPLANATION The keyword function is followed by the name of the function dir. (Sometimes empty parentheses follow the function name, but they are not necessary.) The commands within the curly braces will be executed when dir is typed. The purpose of the function is to list only the subdirectories below the present working directory. The spaces surrounding the first curly brace are required. 14.7.1 Unsetting FunctionsTo remove a function from memory, use the unset command. FORMAT unset -f function_name 14.7.2 Exporting FunctionsFunctions may be exported so that subshells know about them. FORMAT export -f function_name 14.7.3 Function Arguments and the Return ValueBecause the function is executed within the current shell, the variables will be known to both the function and the shell. Any changes made to your environment in the function will also be made to the shell. ArgumentsArguments can be passed to functions by using positional parameters. The positional parameters are private to the function; that is, arguments to the function will not affect any positional parameters used outside the function. See Example 14.56. The Built-In local FunctionTo create local variables that are private to the function and will disappear after the function exits, use the built-in local function. See Example 14.57. The Built-In return FunctionThe return command can be used to exit the function and return control to the program at the place where the function was invoked. (Remember, if you use exit anywhere in your script, including within a function, the script terminates.) The return value of a function is really just the value of the exit status of the last command in the script, unless you give a specific argument to the return command. If a value is assigned to the return command, that value is stored in the ? variable and can hold an integer value between 0 and 256. Because the return command is limited to returning only an integer between 0 and 256, you can use command substitution to capture the output of a function. Place the entire function in parentheses preceded by a $ (e.g., $(function_name)), or traditional backquotes to capture and assign the output to a variable just as you would if getting the output of a UNIX command. Example 14.56.(Passing Arguments) (The Script) #!/bin/bash # Scriptname: checker # Purpose: Demonstrate function and arguments 1 function Usage { echo "error: $*" 2>&1; exit 1; } 2 if (( $# != 2 )) then 3 Usage "$0: requires two arguments" fi 4 if [[ ! ( -r $1 && -w $1 ) ]] then 5 Usage "$1: not readable and writable" fi 6 echo The arguments are: $* < Program continues here > (The Command Line and Output) $ checker error: checker: requires two arguments $ checker file1 file2 error: file1: not readable and writable $ checker filex file2 The arguments are filex file2 EXPLANATION
Example 14.57.(Using the return Command) (The Script) #!/bin/bash # Scriptname: do_increment 1 increment () { 2 local sum; # sum is known only in this function 3 let "sum=$1 + 1" 4 return $sum # Return the value of sum to the script } 5 echo –n "The sum is " 6 increment 5 # Call function increment; pass 5 as a # parameter; 5 becomes $1 for the increment function 7 echo $? # The return value is stored in $? 8 echo $sum # The variable "sum" is not known here (The Output) 4,6 The sum is 6 8 EXPLANATION
Example 14.58.(Using Command Substitution) (The Script) #!/bin/bash # Scriptname: do_square 1 function square { local sq # sq is local to the function let "sq=$1 * $1" echo "Number to be squared is $1." 2 echo "The result is $sq " } 3 echo "Give me a number to square. " read number 4 value_returned=$(square $number) # Command substitution 5 echo "$value_returned" (The Command Line and Output) $ do_square 3 Give me a number to square. 10 5 Number to be squared is 10. The result is 100 EXPLANATION
14.7.4 Functions and the source (or dot) CommandStoring FunctionsFunctions are often defined in the .profile file so that when you log in, they will be defined. Functions can be exported, and they can be stored in a file. Then when you need the function, the source or dot command is used with the name of the file to activate the definitions of the functions within it. Example 14.59.1 $ cat myfunctions 2 function go() { cd $HOME/bin/prog PS1='`pwd` > ' ls } 3 function greetings() { echo "Hi $1! Welcome to my world." ; } 4 $ source myfunctions 5 $ greetings george Hi george! Welcome to my world. EXPLANATION
Example 14.60.(The dbfunctions file shown below contains functions to be used by the main program. See cd for complete script.) 1 $ cat dbfunctions 2 function addon () { # Function defined in file dbfunctions 3 while true do echo "Adding information " echo "Type the full name of employee " read name echo "Type address for employee " read address echo "Type start date for employee (4/10/88 ) :" read startdate echo $name:$address:$startdate echo –n "Is this correct? " read ans case "$ans" in [Yy]*) echo "Adding info..." echo $name:$address:$startdate>>datafile sort –u datafile –o datafile echo –n "Do you want to go back to the main menu? " read ans if [[ $ans == [Yy] ]] then 4 return # Return to calling program else 5 continue # Go to the top of the loop fi ;; *) echo "Do you want to try again? " read answer case "$answer" in [Yy]*) continue;; *) exit;; esac ;; esac done 6 } # End of function definition ------------------------------------------------------------- (The Command Line) 7 $ more mainprog #!/bin/bash # Scriptname: mainprog # This is the main script that will call the function, addon datafile=$HOME/bourne/datafile 8 source dbfunctions # The file is loaded into memory if [ ! –e $datafile ] then echo "$(basename $datafile) does not exist" >&2 exit 1 fi 9 echo "Select one: " cat <<EOF [1] Add info [2] Delete info [3] Update info [4] Exit EOF read choice case $choice in 10 1) addon # Calling the addon function ;; 2) delete # Calling the delete function ;; 3) update ;; 4) echo Bye exit 0 ;; *) echo Bad choice exit 2 ;; esac echo Returned from function call echo The name is $name # Variable set in the function are known in this shell. done EXPLANATION
|
< Day Day Up > |