基本语法
#函数定义
function funname()
{
Action;
[return int;]
}
#函数调用
funname
注:
(1)在调用函数地方之前,先声明函数,shell脚本是逐行运行。
(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值,return后跟数值n(0-255)。
例子
计算两个数的和
[mubai@localhost test]$ touch sum.sh
[mubai@localhost test]$ vim sum.sh
#!/bin/bash
function sum()
{
s=0
s=$[ $1 + $2 ]
echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
[mubai@localhost test]$ chmod 777 sum.sh
[mubai@localhost test]$ ./sum.sh
Please input the number1: 2
Please input the number2: 5
7