Function
Bash does not enable a new sub-shell to call a function. It is executed in the existing shell environment.
Syntax:
Function Name ()
{
Command Area
}
Function Name ()
{
Command Area
}
Function Name
{
Command Area
}
Call: function name parameter 1 parameter 2 ....
FUNCNAME variable, whose value is the function name
Cancel Function Definition: unset-f function name
Return command $? Return Value
Function scope: the function is valid only in the defined shell environment. If you want to pass the function to the sub-shell environment, you can use the built-in command export and-f option: export-f function name.
If no special attribute is set for a variable, the custom variable in the script is called a global variable and its scope is in the entire script file.
Built-in command local, set the variable property to private
In the main program, do not use the value of the global variable passed in the function to control the program flow after the function is executed.
Location parameters
Description
Shift n
Specify the location parameter: set command
Example
#! /Bin/bash
Declare-I = 0
Set 61 62 63 64 65 66 67 68 69 70
For p in $ @
Do
(I ++ ))
Echo "parameter $ I position \ $ I = $ p"
Done
When the parameter value is passed to the function using the location parameter, the original location parameter will be saved, and its contained value will not be affected.
Use the options and parameters of the command line:
Getopts option row option variable
The option line consists of a single character of each option. getopts acquires the option from the command line and puts it into the option variable. If this option requires additional parameters, the parameter value will be placed in the OPTARG variable.
Example
#! /Bin/bash
While getopts u: ah opt
Do
Case $ opt in
U)
Echo "provides options u and parameters: $ OPTARG ";;
A)
Echo "provides option ";;
H)
Echo "provides the option h ";;
*)
;;
Esac
Done
Create a function library
Recursive functions
Example
#! /Bin/bash
Function factor_in (){
Local tmp
Local tmp1
Tmp = "$1"
If [$ tmp-eq 1]; then
Echo-n "1"
R = 1
Else
Echo-n "$ tmp *"
Tmp1 = $ tmp
Tmp = $ ($ tmp-1 ))
Factor_in $ tmp
R = $ ($ tmp * $ r ))
Fi
}
If [$ #-ne 1]; then
Echo "Usage: $0 positive integer"
Exit 1
Fi
Echo
Echo-n $1 "! ="
Factor_in $1
Echo-n "= $ r"
Echo
Result