- Like "real" programming languages, Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a "black box" that performs a specified task.
- Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function.
function function_name {
command...
}
or
function_name () {
command...
}
- A function may be "compacted" into a single line.
fun () { echo "This is a function"; echo; }
- Functions are called, triggered, simply by invoking their names.
Exit and Return
exit status
Functions return a value, called an exit status. The exit status may be explicitly specified by a return statement, otherwise it is the exit status of the last command in the function (0 if successful, and a non-zero error code if not). This exit status may be used in the script by referencing it as $?. This mechanism effectively permits script functions to have a "return value" similar to C functions.
return
Terminates a function. A return command [86] optionally takes an integer argument, which is returned to the calling script as the "exit status" of the function, and this exit status is assigned to the variable $?.
The largest positive integer a function can return is 255.
Ex.
#!/bin/bash
# realname.sh
#
# From username, gets "real name" from /etc/passwd.
ARGCOUNT=1 # Expect one arg.
E_WRONGARGS=65
file=/etc/passwd
pattern=$1
if [ $# -ne "$ARGCOUNT" ]
then
echo "Usage: `basename $0` USERNAME"
exit $E_WRONGARGS
fi
file_excerpt () # Scan file for pattern, then print relevant portion of line.
{
while read line # "while" does not necessarily need "[ condition ]"
do
echo "$line" | grep $1 | awk -F":" '{ print $5 }' # Have awk use ":" delimiter.
done
} <$file # Redirect into function's stdin.
file_excerpt $pattern
What makes a variable local?
A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope." In a function, a local variable has meaning only within that function block.
#!/bin/bash
# Global and local variables inside a function.
func ()
{
local loc_var=23 # Declared as local variable.
echo # Uses the 'local' builtin.
echo "\"loc_var\" in function = $loc_var"
global_var=999 # Not declared as local.
# Defaults to global.
echo "\"global_var\" in function = $global_var"
}
func
# Now, to see if local variable "loc_var" exists outside function.
echo "\"loc_var\" outside function = $loc_var"
echo "\"global_var\" outside function = $global_var"
- A function calling himself known as Function Recursion.

No comments:
Post a Comment