Shell function
Linux shell allows users to define functions, which can then be called at will in shell scripts.
The definition format of functions in shell is as follows:
[ function ] funname [()] { action; [return int;] }
Instructions:
1. You can define it with function fun(), or you can directly fun( ) definition without any parameters.
2. Parameter return, you can add: return to display. If not, the result of running the last command will be used as the return value. return followed by the value n(0-255
The following example defines a function and calls it:
#!/bin/bash # author:php中文网 # url:www.php.cn demoFun(){ echo "这是我的第一个 shell 函数!" } echo "-----函数开始执行-----" demoFun echo "-----函数执行完毕-----"
Output result:
-----函数开始执行----- 这是我的第一个 shell 函数! -----函数执行完毕-----
Definition below A function with a return statement:
#!/bin/bash # author:php中文网 # url:www.php.cn funWithReturn(){ echo "这个函数会对输入的两个数字进行相加运算..." echo "输入第一个数字: " read aNum echo "输入第二个数字: " read anotherNum echo "两个数字分别为 $aNum 和 $anotherNum !" return $(($aNum+$anotherNum)) } funWithReturn echo "输入的两个数字之和为 $? !"
The output is similar to the following:
这个函数会对输入的两个数字进行相加运算... 输入第一个数字: 1 输入第二个数字: 2 两个数字分别为 1 和 2 ! 输入的两个数字之和为 3 !
The function return value is obtained through $? after calling the function
Note: All functions. Must be defined before use. This means that the function must be placed at the beginning of the script and cannot be used until the shell interpreter first discovers it. Just use its function name. Function parameters
In Shell, parameters can be passed to a function when calling it. Inside the function body, the value of the parameter is obtained in the form of $n. For example, $1 represents the first parameter and $2 represents the second parameter. Parameters...Example of function with parameters:
#!/bin/bash # author:php中文网 # url:www.php.cn funWithParam(){ echo "第一个参数为 !" echo "第二个参数为 !" echo "第十个参数为 !" echo "第十个参数为 !" echo "第十一个参数为 !" echo "参数总数有 $# 个!" echo "作为一个字符串输出所有参数 $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73Output result:
第一个参数为 1 ! 第二个参数为 2 ! 第十个参数为 10 ! 第十个参数为 34 ! 第十一个参数为 73 ! 参数总数有 11 个! 作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 !Note that $10 cannot obtain the tenth parameter, and it is necessary to obtain the tenth parameter ${10}. When n>=10, you need to use ${n} to get the parameters. In addition, there are several special characters used to process parameters:
$ | |
---|---|
$* | |
$$ | |
$! | |
$@ | |
$- | |
$? | |