加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell 函数

发布时间:2020-12-15 23:05:59 所属栏目:安全 来源:网络整理
导读:只举三个例子,不带返回值的,带返回值的和传递参数的,由此就可以知道在shell中如何使用函数。 一、没有返回值 demoFun() { echo " this is a function " }调用 echo " ---------- " demoFun echo ‘ ----------- ‘ 结果: -------- this is a function --

只举三个例子,不带返回值的,带返回值的和传递参数的,由此就可以知道在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读