Shell script (5)-function
One, shell function definition
- Write the command sequence together in a format to facilitate repeated use of the command sequence
Two, format
1. Format 1:
function 函数名 {
命令序列
}
2. Format 2:
函数名() {
命令序列
}
Three, function return value
-
return means to exit the function and return an exit value, which can be displayed by the $? variable in the script
-
Principle of use:
- 1. Take the return value as soon as the function ends, because the $? variable only returns the exit status code of the last command executed
- 2. The exit status code must be 0~255, and the value will be divided by 256 when it is exceeded.
Four, function parameter transfer
Five, 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
Six, recursion
1. Factorial
2. Recursive search directory
Seven, create a function library
Put commonly used functions into a separate library script, so that when the script is in use, you can directly call the functions in this library