1、函数定义:
function 函数名()
{
command
command
[return value]
}
2、函数调用例子:
function myPrint()
{
echo "1"
echo "2"
echo "3"
}
myPrint
echo "4"
结果为:
echo "1"
echo "2"
echo "3"
echo "4"
注意:如果myPrint存在返回值,那么通过$myPrint可以得到返回值
3、带参数函数定义:
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...
4、带参数函数调用:
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 !"
5、shell 函数中带数组
a=(1 2 3)
b=(a b c)
fun()
{
local
a=($1)
local
b=($2)
echo
${a[*]}
echo
${b[*]}
}
fun
"${a[*]}"
"${b[*]}