shell函数

Shell 函数的定义格式如下:
function_name () {
list of commands
[ return value ]
}
也可以在函数名前面加上关键字 function:
function function_name () {
list of commands
[ return value ]
}
函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。
shell 函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败。如果return其他数据,比如一个字符串,往往会得到错误提示:"numeric argument required"
如果一定要让函数返回字符串,name可以先定义一个变量。用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。

#!/bin/bash
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"

像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 -f 选项,如下所示:

unset -f funWithReturn

如果你希望直接从终端调用函数,可以将函数定义在主目录下的 .profile 文件,这样每次登录后,在命令提示符后面输入函数名字就可以立即调用。

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...
带参数的函数例子:

funWithParam(){
echo "The value of the first parameter is $1 !"
echo "The value of the second parameter is $2 !"
echo "The value of the tenth parameter is $10 !"
echo "The value of the tenth parameter is ${10} !"
echo "The value of the eleventh parameter is ${11} !"
echo "The amount of the parameters is $# !"  # 参数个数
echo "The string of the parameters is $* !"  # 传递给函数的所有参数
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

warn:10 不能获取第十个参数,获取第十个参数需要{10}。当n>=10时,需要使用${n}来获取参数。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,500评论 0 5
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,950评论 0 38
  • 来源: Linux命令行与shell脚本编程大全 博客地址,推荐电脑点 内容 基本的脚本函数返回值在函数中使用变量...
    王诗翔阅读 2,485评论 0 3
  • 12岁的阿富汗富家少爷阿米尔与仆人哈桑情同手足。然而,在一场风筝比赛后,发生了一件悲惨不堪的事,阿米尔为自己的懦弱...
    cc57886fd23a阅读 194评论 0 0
  • 回学校的第三天,还是一个人。天气很冷,显得宿舍里更冷清。原本以为早些回到学校能够促使自己捡起学习这件大事,但是事实...
    shinydant阅读 641评论 0 0