shell脚本的简单使用:七——之函数使用

shell种的函数
函数有两个优势:

1. 将处理相同事情的一系列的调用的统一,代码利用率高,
2. 复杂的功能和模块拆分,便于代码的可读性


#简单函数1
function1(){
 echo "function1"
}
#简单函数2
function function2(){
 echo "function function2"
}
#记得加上,要不然就是注释了
function1
function2

#带返回值的函数
returnFunction(){
 return `expr $1 + $2`
}

returnFunction $1 $2
rv=$?
echo "reture value is $rv"

#在来一个大家都用的例子
funWithReturn(){
 echo "get sum value of two number"
 echo -n "input first number:"
  read num1
 echo -n "input second number"
  read num2
 echo "your input numbers are $num1 and $num2"
 return "$(($num1+$num2))"
}
funWithReturn
rv=$?
echo "function funWithReturn return $rv"

#函数之间的调用
call_f(){
 echo "this is function1"
 call_f2
}
call_f2(){
 echo "this is function2"
}
call_f

#删除方法
unset -f call_f2
call_f

运行命令sh function.sh 1 2 后的结果
function1
function function2
reture value is 3
get sum value of two number
input first number:3
input second number3
your input numbers are 3 and 3
function funWithReturn return 6
this is function1
this is function2
this is function1
function.sh: line 44: call_f2: command not found

函数中参数的传递
$#	传递给函数的参数个数。
$*	显示所有传递给函数的参数。
$@	与$*相同,但是略有区别,在某些操作中该操作会拆分
$?	函数的返回值。

具体的脚本
#函数中传递参数
funWithParam(){
 echo "paragram 1 $1"
 echo "paragram 2 $2"
 echo "paragram 3 $3"
 echo "paragram 4 $4"
 echo "paragram 5 $5"
 echo "paragram number $#"
 echo "paragram all $@"
}
funWithParam 1 2 3 4 5 6 7

执行后的结果
paragram 1 1
paragram 2 2
paragram 3 3
paragram 4 4
paragram 5 5
paragram number 7
paragram all 1 2 3 4 5 6 7

猜你喜欢

转载自janle.iteye.com/blog/2368261