Catalog title
shell function
Functions can be defined by the user, and then can be called casually in the shell script
Function format
method 1
function 函数名 {
命令序列
}
Method 2
函数名 () {
命令序列
}
Function return value return
- return means to exit the function and return an exit value, which can be displayed by the $? variable in the script
- The return value is taken as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
- The exit status code must be 0-255, the excess value will be divided by 256 to take the remainder
Function parameters
- In the Shell, that can be passed when calling the function parameters in
$1
,$2
,$3
,$4
...$#
,$*
indicating the call back function parameters with
an outer and function$1
,$2
... keyboard input value after the call to the script file - As shown
- Example: The value accumulated from 1 to 10 is calculated by passing parameters
- Multiply the added value by 2
by assigning a function
The scope of function variables
- Functions in Shell scripts are only valid in the current Shell environment
- Variables in Shell scripts are globally effective by default
- Use the local command to limit the variable to the function
Recursion
- Function calls its own function
- Factorial example
#分析思路比如输入5时
fact 5
$1=5 temp=4 result=fact 4 echo 5 * (4 * (3 * (2 * (1))))
fact4
$1=4 temp=3 result=fact 3 echo 4 * (fact 3)
fact3
$1=3 temp=2 result=fact 2 echo 3 * (fact 2)
fact2
$1=2 temp=1 result=fact 1 echo 2 * (fact 1)
fact1
1
Recursive directory
Recursively view the directories and files in the /var/log directory
Function library
-
The function of the function library: write the functions that implement the same type of function in the same script file for easy classification, and you can call it directly when you use the function
-
Define a simple algorithm function library. The functions in the library are as follows
-
Addition function add
-
Subtraction function
-
Multiplication function
-
Divide function divider
-
Call the function in the function library