demoFun(){ echo"This is my first shell function!" } echo"-----Execution-----" demoFun echo"-----Finished-----"
Output the result: -----Execution----- This is my first shell function! -----Finished-----
下面定义一个带有 return 语句的函数:
1 2 3 4 5 6 7 8 9 10 11 12
#!/bin/bash funWithReturn(){ echo"This function will add the two numbers of the input..." echo"Enter the first number: " read aNum echo"Enter the second number: " read anotherNum echo"The two numbers are $aNum and $anotherNum !" return $(($aNum+$anotherNum)) } funWithReturn echo"The sum of the two numbers entered is $? !"
输出类似下面:
1 2 3 4 5 6 7
This function will add the two numbers of the input... Enter the first number: 1 Enter the second number: 2 The two numbers are 1 and 2 ! The sum of the two numbers entered is 3 !
#!/bin/bash funWithParam(){ echo"The first parameter is $1 !" echo"The second parameter is $2 !" echo"The tenth parameter is $10 !" echo"The tenth parameter is ${10} !" echo"The eleventh parameter is ${11} !" echo"The total number of parameters is $# !" echo"Outputs all parameters as a string $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73
输出结果:
1 2 3 4 5 6 7
The first parameter is 1 ! The second parameter is 2 ! The tenth parameter is 10 ! The tenth parameter is 34 ! The eleventh parameter is 73 ! The total number of parameters is 11 ! Outputs all parameters as a string 1 2 3 4 5 6 7 8 9 34 73 !
注意
10 不能获取第十个参数,获取第十个参数需要 {10}。当 n >= 10 时,需要使用 ${n} 来获取参数