Shell函数的7种用法介绍
1.在shell文件内部定义函数并引用:
[~/shell/function]#catfactorial.sh
#!/bin/bash
functionfactorial
{
factorial=1
for((i=1;i<=$1;i++))
do
factorial=$[$factorial*$i]
done
echo$1的阶乘是:$factorial
}
echo'程序名':$0,用于求阶乘
factorial$1
[~/shell/function]#./factorial.sh10
程序名:./factorial.sh,用于求阶乘
10的阶乘是:3628800
2.返回值
函数返回码是指函数最后一条命令的状态码,可以用于函数返回值
使用return命令手动指定返回值:
[~/shell/function]#catreturn.sh
#!/bin/bash
functionfun1{
read-p"entera:"a
echo-n"print2a:"
return$[$a*2]
}
fun1
echo"returnvalue$?"
[~/shell/function]#./return.sh
entera:100
print2a:returnvalue200
由于shell状态码最大是255,所以当返回值大于255时会出错。
[~/shell/function]#./return.sh entera:200 print2a:returnvalue144
3.函数输出
为了返回大于255的数、浮点数和字符串值,最好用函数输出到变量:
[~/shell/function]#cat./fun_out.sh
#!/bin/bash
functionfun2{
read-p"entera:"a
echo-n"print2a:"
echo$[$a*2]
}
result=`fun2`
echo"returnvalue$result"
[~/shell/function]#./fun_out.sh
entera:400
returnvalueprint2a:800
4.向函数传递参数(使用位置参数):
[~/shell/function]#cat./parameter.sh
#!/bin/bash
if[$#-ne3]
then
echo"usage:$0abc"
exit
fi
fun3(){
echo$[$1*$2*$3]
}
result=`fun3$1$2$3`
echotheresultis$result
[~/shell/function]#./parameter.sh 123
theresultis6
[~/shell/function]#./parameter.sh 12
usage:./parameter.shabc
5.全局变量与局部变量
默认条件下,在函数和shell主体中建立的变量都是全局变量,可以相互引用,当shell主体部分与函数部分拥有名字相同的变量时,可能会相互影响,例如:
[~/shell/function]#cat./variable.sh
#!/bin/bash
if[$#-ne3]
then
echo"usage:$0abc"
exit
fi
temp=5
value=6
echotempis:$temp
echovalueis:$value
fun3(){
temp=`echo"scale=3;$1*$2*$3"|bc-ql`
result=$temp
}
fun3$1$2$3
echo"theresultis$result"
if[`echo"$temp>$value"|bc-ql`-ne0]
then
echo"tempislarger"
else
echo"tempisstillsmaller"
fi
[~/shell/function]#./variable.sh 1232
tempis:5
valueis:6
theresultis72
tempislarger
在这种情况下,在函数内部最好使用局部变量,消除影响。
[~/shell/function]#cat./variable.sh
#!/bin/bash
if[$#-ne3]
then
echo"usage:$0abc"
exit
fi
temp=5
value=6
echotempis:$temp
echovalueis:$value
fun3(){
localtemp=`echo"scale=3;$1*$2*$3"|bc-ql`
result=$temp
}
fun3$1$2$3
echo"theresultis$result"
if[`echo"$temp>$value"|bc-ql`-ne0]
then
echo"tempislarger"
else
echo"tempisstillsmaller"
fi
[~/shell/function]#./variable.sh 1232
tempis:5
valueis:6
theresultis72
tempisstillsmaller
6.向函数传递数组变量:
[~/shell/function]#catarray.sh
#!/bin/bash
a=(1112131415)
echo${a[*]}
functionarray(){
echoparameters:"$@"
localfactorial=1
forvaluein"$@"
do
factorial=$[$factorial*$value]
done
echo$factorial
}
array${a[*]}
[~/shell/function]#./array.sh
1112131415
parameters:1112131415
360360
7.函数返回数组变量
[~/shell/function]#catarray1.sh
#!/bin/bash
a=(1112131415)
functionarray(){
echoparameters:"$@"
localnewarray=(`echo"$@"`)
localelement="$#"
locali
for((i=0;i<$element;i++))
{
newarray[$i]=$[${newarray[$i]}*2]
}
echo newvalue:${newarray[*]}
}
result=`array${a[*]}`
echo${result[*]}
[~/shell/function]#./array1.sh
parameters:1112131415newvalue:2224262830