输出: Function begin... This is your first shell function! Function end! 下面定义一个带有return语句的函数: 复制代码 代码如下: #!/bin/bash funWithReturn(){ echo "The function is to get the sum of two numbers..." echo -n "Input first number: " read aNum echo -n "Input another number: " read anotherNum echo "The two numbers are $aNum and $anotherNum !" return $(($aNum+$anotherNum)) } funWithReturn echo "The sum of two numbers is $? !"
输出类似下面: The function is to get the sum of two numbers... Input first number: 25 Input another number: 50 The two numbers are 25 and 50 ! The sum of two numbers is 75 ! 函数返回值在调用该函数后通过 $? 来获得。 注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。 二、Shell函数参数 在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数... 带参数的函数示例: 复制代码 代码如下: #!/bin/bash funWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is $10 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !" echo "The string of the parameters is $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73
输出: The value of the first parameter is 1 ! The value of the second parameter is 2 ! The value of the tenth parameter is 10 ! The value of the tenth parameter is 34 ! The value of the eleventh parameter is 73 ! The amount of the parameters is 12 ! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !" 注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。 另外,还有几个特殊字符用来处理参数: