in the In a Shell script, some operations that need to be reused are defined as public statement blocks, which can be called functions
What are the benefits of using functions?
Make script code more concise, enhance readability and improve execution efficiency of shell scripts
function Definition Method
Basic Format 1
function function name { function body }
Format 2:
Function name () {function body}
Note: The function name is defined and will not be output
rules when using a function:
defined after the call; can only be defined not called in the same script, the function name in the same time, after the definition of the function name distinguishes the letter case is defined in the function of the variable is a local variable, can only be used within the current function of the function is defined outside the body of the variable is a global variable, Global variables all functions can be defined once with each other using functions, and the bash call function can be reused multiple times without opening a new child shell, which executes the function in an existing shell environment
Define the function sum.two in the fun.sh script(the function is the sum of the output number, and the output of the calculation result)
[email protected] shell]# cat sum_two.sh#!/bin/bashsum_two () {sumten " "}sum_two
create an adder in the script that sums 2 integers
[[email protected] shell]# Cat funadder.sh #!/bin/Bashadder () { echo $ ($1+$2 789
functions in the service script
Suitable for complex start/ stop control operations to facilitate multiple calls when required
Recursive invocation Example
Shell version of the fork bomb
Only 13 characters:. (){.|. & };. Recursive dead loops that can quickly drain system resources
Unlimited generation of new processes, resulting in the crash
Code parsing
. () #定义一个名为. The function { #函数块的开始标记. & #在后台递归调用函数.; #函数块的结束标记. #再次调用函数
Functions can be called recursively (functions call themselves)
Eight using Shell functions