Section 6.11. Functions


[Page 232 (continued)]

6.11. Functions

Bash allows you to define functions that may be invoked as shell commands. Parameters passed to functions are accessible via the standard positional parameter mechanism. Functions must be defined before they are used. There are two ways to define a function, as shown in Figure 6-35.

Figure 6-35. A Bash function declaration.


function name
{
   list of commands
}
         or the keyword function may be omitted:
name ()
{
   list of commands.
}


To invoke a function, supply its name followed by the appropriate parameters. For obvious reasons, the shell does not check the number or type of the parameters.

Here's an example of a script that defines and uses a function that takes no parameters:

$ cat func1.sh            ...list the script. message ()      # no-parameter function. {  echo hi  echo there } i=1 while (( i <= 3 )) do  message   # call the function.  let i=i+1 # increment loop count. done $ sh func1.sh             ...execute the script. hi there 
[Page 233]
hi there hi there $ _


6.11.1. Using Parameters

As I mentioned previously, parameters are accessible via the standard positional mechanism. Here's an example of a script that passes parameters to a function:

$ cat func2.sh               ...list the script. f () {  echo parameter 1 = $1      # display first parameter.  echo parameter list = $*   # display entire list. } # main program. f 1                          # call with 1 parameter. f cat dog goat               # call with 3 parameters. $ sh func2.sh                   ...execute the script. parameter 1 = 1 parameter list = 1 parameter 1 = cat parameter list = cat dog goat $ _ 


6.11.2. Returning from a Function

The return command returns the flow of control back to the caller, and has the following syntax shown in Figure 6-36.

Figure 6-36. Bash function return statement.

return [ value ]


When return is used without an argument, the function call returns immediately with the exit code of the last command that was executed in the function; otherwise, it returns with its exit code set to value. If a return command is executed from the main script, it's equivalent to an exit command. The exit code is accessible from the caller via the $? variable. Here's an example function that multiplies its arguments and returns the result:

$ cat func3.sh          ...list the script. f ()     # two-parameter function. {  (( returnValue = $1 * $2 )) 
[Page 234]
return $returnValue } # main program. f 3 4 # call function. result=$? # save exit code. echo return value from function was $result $ sh func3.sh ...execute the script. return value from function was 12 $ _


6.11.3. Access to Functions

Functions can be exported to subshells in Bash. This is accomplished with the export built-in, described in Figure 6-37.

Figure 6-37. Description of the export shell command used to export a function.

Shell command: export -f functionname

The export built-in command used with the -f option exports a function to a subshell the same way exported shell variable values are exported to subshells.


Bash also provides a built-in command called local (Figure 6-38) to restrict a variable to be local only to the current function (i.e., its value cannot be passed to a subshell).

Figure 6-38. Description of the local shell command.

Shell command: local name[=value]

The local built-in command defines a variable to be local only to the current function. A variable name can be listed or a value can be assigned in the same statement.


Another useful built-in command used when writing functions is the builtin built-in command (Figure 6-39).

Figure 6-39. Description of the builtin shell command.

Shell command: builtin [command [args] ]

The builtin shell built-in runs the named shell built-in command, and passes it args if present. This is useful when you are writing a shell function that has the same name as an existing built-in but within the function you still want to run the built-in rather than recursively call the function.



[Page 235]

6.11.4. Recursion

With careful thought, it's perfectly possible to write recursive functions. Here are two example scripts that implement a recursive version of factorial (). The first uses the exit code to return the result and the second uses standard output to echo the result. Note these scripts are available online; see the Preface for more information.

6.11.4.1. Recursive Factorial, Using Exit Code

factorial ()       # one-parameter function {  if (( $1 <= 1 ))   then     return 1                  # return result in exit code.   else     typeset tmp               # declare two local variables.     typeset result     (( tmp = $1 - 1 ))     factorial $tmp            # call recursively.     (( result = $? * $1 ))     return $result            # return result in exit code.   fi } # main program. factorial 5                   # call function echo factorial 5 = $?         # display exit code. 


6.11.4.2. Recursive Factorial, Using Standard Output

factorial()        # one-parameter function {  if (( $1 <= 1 ))   then     echo 1                    # echo result to standard output.   else     typeset tmp               # declare two local variables.     typeset result     (( tmp = $1 - 1 ))     (( result = 'factorial $tmp' * $1 ))     echo $result        # echo result to standard output.   fi } # echo factorial 5 = 'factorial 5'     # display result. 



[Page 236]

6.11.5. Sharing Functions

To share the source code of a function between several scripts, place it in a separate file and then read it using the "." or source built-in commands at the start of the scripts that use the function (Figure 6-40).

Figure 6-40. Description of the source and "." shell commands.


Shell Commandsource fileName
        . fileName

source (or ".") causes a shell to execute every command in the script called fileName without invoking a subshell. It is perfectly legal for fileName to contain further source commands. If an error occurs during the execution of fileName, control is returned to the original shell.


In the following example, assume that the source code of one of the previous factorial scripts was saved in a file called "fact.sh":

$ cat script.sh                      ...list the script. . fact.sh                  # read function source code. echo factorial 5 = 'factorial 5'   # call the function. $ sh script.sh                       ...execute the script. factorial 5 = 120 $ _ 





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

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