Shell 函数
shell函数定义
- 1、可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。
- 2、参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255)
函数参数
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数... 注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。
函数示例:
$ funWithParam()
{
echo "The first para $1 !"
echo "The second para $2 !"
echo "The tenth para $10 !"
echo "The tenth para ${10} !"
echo "The total para $# !"
echo "output as a string $* !"
echo `date`
}
#运行结果如下
$ funWithParam 1 2 3 4 5 6 7 8 9 55 66 77
The first para 1 !
The second para 2 !
The tenth para 10 !
The tenth para 55 !
The total para 12 !
output as a string 1 2 3 4 5 6 7 8 9 55 66 77 !
2018年10月10日 14:00:48