shell 函数

只举三个例子,不带返回值的,带返回值的和传递参数的,由此就可以知道在shell中如何使用函数。

一、没有返回值

demoFun() {
 echo "this is a function"   
}

调用
echo "----------"
demoFun
echo '-----------'

结果:
--------
this is a function
--------

 

二、带返回值

若不加return语句,将以最后一条命令的运行结果作为返回值。

funWithReturn() {
 read aNum
 read anotherNum
 return $(($aNum+$anotherNum))   
}

echo "input: "
funWithReturn
echo "value is: $?" #函数返回值在调用该函数后通过$?来获得。

所有函数在使用前必须定义,必须将函数放在脚本开始部分,直至shell解释器发现,才可以使用。

 

三、传递参数

在函数内部通过$n的形式获取参数的值,$1为第一个参数,$2为第二个参数。

funWithParam() {
 echo "first $1"
 echo "second $2"
 echo "third $3"
 echo "tenth ${10}"   #当n>=10时,需要通过${n}来获取参数。
}
调用:
funWithParam 1 2 3 4 5 6

 

posted @ 2018-12-28 12:16  c++11  阅读(230)  评论(0编辑  收藏  举报