Shell脚本函数定义和函数参数
一、Shell函数
本教程目前为止所有脚本都是从头到尾执行。这样做很好,但你也许已经注意到有些脚本段间互相重复。
shell允许将一组命令集或语句形成一个可用块,这些块称为shell函数。
shell中函数的定义格式如下:
函数名(){ command1 command2 ... commandN [returnvalue] }
如果愿意,可在函数名前加上关键字function,这取决于使用者。
function函数名(){ command1 command2 ... commandN [returnvalue] }
函数返回值,可以显示增加return语句;如果不加,则将最后一条命令运行结果作为返回值(一般为0,如果执行失败则返回错误代码)。return后跟数值(0-255)。
函数可以放在同一个文件中作为一段代码,也可以放在只包含函数的单独文件中。函数不必包含很多语句或命令,甚至可以只包含一个echo语句,这取决于使用者。
下面的例子定义了一个函数并进行调用:
#!/bin/bash demoFun(){ echo"Thisisyourfirstshellfunction!" } echo"Functionbegin..." hello echo"Functionend!"
输出:
Functionbegin...
Thisisyourfirstshellfunction!
Functionend!
下面定义一个带有return语句的函数:
#!/bin/bash funWithReturn(){ echo"Thefunctionistogetthesumoftwonumbers..." echo-n"Inputfirstnumber:" readaNum echo-n"Inputanothernumber:" readanotherNum echo"Thetwonumbersare$aNumand$anotherNum!" return$(($aNum+$anotherNum)) } funWithReturn echo"Thesumoftwonumbersis$?!"
输出类似下面:
Thefunctionistogetthesumoftwonumbers...
Inputfirstnumber:25
Inputanothernumber:50
Thetwonumbersare25and50!
Thesumoftwonumbersis75!
函数返回值在调用该函数后通过$?来获得。
注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。
二、Shell函数参数
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过$n的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...
带参数的函数示例:
#!/bin/bash funWithParam(){ echo"Thevalueofthefirstparameteris$1!" echo"Thevalueofthesecondparameteris$2!" echo"Thevalueofthetenthparameteris$10!" echo"Thevalueofthetenthparameteris${10}!" echo"Thevalueoftheeleventhparameteris${11}!" echo"Theamountoftheparametersis$#!" echo"Thestringoftheparametersis$*!" } funWithParam1234567893473
输出:
Thevalueofthefirstparameteris1!
Thevalueofthesecondparameteris2!
Thevalueofthetenthparameteris10!
Thevalueofthetenthparameteris34!
Thevalueoftheeleventhparameteris73!
Theamountoftheparametersis12!
Thestringoftheparametersis1234567893473!"
注意,$10不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。
另外,还有几个特殊字符用来处理参数: