用户可以用shell定义函数,然后子啊shell脚本中随便调用。shell中函数的定义格式如下:
[ function ] funname [()]
{
action;
[return int;]
}
- 可以带
function fun()定义,也可以直接fun()定义,不带任何参数。 - 参数返回,可以显示加:
return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值 n(0-255)
不含 return
demoFun(){
echo "This is my first function"
}
echo "-----func start-----"
demoFun
echo "-----func end-----"
包含 return
funWithReturn(){
echo "add action"
echo "input first num: "
read aNum
echo "input second num: "
read anotherNum
echo "The two nums are $aNum and $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn
echo "The total of two nums are $? "
函数返回值在调用该函数后通过 $? 来获得。
注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至shell解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。
函数参数
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1 表示第一个参数,$2 表示第二个参数 ……
funWithParam(){
echo "first : $1 "
echo "second : $2 "
echo "tenth : $10 "
echo "tenth : ${10} "
echo "eleventh : ${11} "
echo "total num : $# "
echo "the single string : $* "
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
注意:$10 不能获取第十个参数,获取第十个参数需要 ${10} 。当 n>=10 时,需要使用 ${n} 来获取参数。
本文介绍了如何在Shell脚本中定义和使用函数。包括函数的基本定义格式、参数传递方式及返回值处理等内容,并通过示例演示了不同类型的函数用法。
1862

被折叠的 条评论
为什么被折叠?



