1.定义函数
[ function ] funname [()]
{
action;
[return int;]
}
可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。
参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255)
#!/bin/bash
funWithReturn(){
echo "This function will add the two numbers of the input..."
echo "Enter the first number: "
read aNum
echo "Enter the second number: "
read anotherNum
echo "The two numbers are $aNum and $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of the two numbers entered is $? !"
函数参数
在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数… 带参数的函数示例
#!/bin/bash
funWithParam(){
echo "The first parameter is $1 !"
echo "The second parameter is $2 !"
echo "The tenth parameter is $10 !"
echo "The tenth parameter is ${10} !"
echo "The eleventh parameter is ${11} !"
echo "The total number of parameters is $# !"
echo "Outputs all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
输出
The first parameter is 1 !
The second parameter is 2 !
The tenth parameter is 10 !
The tenth parameter is 34 !
The eleventh parameter is 73 !
The total number of parameters is 11 !
Outputs all parameters as a string 1 2 3 4 5 6 7 8 9 34 73 !
本文深入探讨Shell脚本中函数的定义与使用,包括无参与有参函数、函数返回值及参数传递方式。通过具体示例展示了如何定义带有返回值的函数以及如何在函数中处理多个参数。
1853

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



