查看: 2037|回复: 0
打印 上一主题 下一主题

Shell函数:Shell函数返回值、删除函数、在终端调用函数

[复制链接]
跳转到指定楼层
沙发
发表于 2014-8-18 10:42:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
函数可以让我们将一个复杂功能划分成若干模块,让程序结构更加清晰,代码重复利用率更高。像其他编程语言一样,Shell 也支持函数。Shell 函数必须先定义后使用。

Shell 函数的定义格式如下:
  1. function_name () {
  2.     list of commands
  3.     [ return value ]
  4. }
复制代码

如果你愿意,也可以在函数名前加上关键字 function:
  1. function function_name () {
  2.     list of commands
  3.     [ return value ]
  4. }
复制代码

函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

Shell 函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败。如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”。

如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。

先来看一个例子:
  1. #!/bin/bash
  2. # Define your function here
  3. Hello () {
  4.    echo "Url is http://see.xidian.edu.cn/cpp/shell/"
  5. }
  6. # Invoke your function
  7. Hello
复制代码

运行结果:
  1. $./test.sh
  2. Hello World
  3. $
复制代码

调用函数只需要给出函数名,不需要加括号。

再来看一个带有return语句的函数:
  1. #!/bin/bash
  2. funWithReturn(){
  3.     echo "The function is to get the sum of two numbers..."
  4.     echo -n "Input first number: "
  5.     read aNum
  6.     echo -n "Input another number: "
  7.     read anotherNum
  8.     echo "The two numbers are $aNum and $anotherNum !"
  9.     return $(($aNum+$anotherNum))
  10. }
  11. funWithReturn
  12. # Capture value returnd by last command
  13. ret=$?
  14. echo "The sum of two numbers is $ret !"
复制代码

运行结果:
  1. The function is to get the sum of two numbers...
  2. Input first number: 25
  3. Input another number: 50
  4. The two numbers are 25 and 50 !
  5. The sum of two numbers is 75 !
复制代码

函数返回值在调用该函数后通过 $? 来获得。

再来看一个函数嵌套的例子:
  1. #!/bin/bash
  2. # Calling one function from another
  3. number_one () {
  4.    echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
  5.    number_two
  6. }
  7. number_two () {
  8.    echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
  9. }
  10. number_one
复制代码

运行结果:
  1. Url_1 is http://see.xidian.edu.cn/cpp/shell/
  2. Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
复制代码

像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 .f 选项,如下所示:
$unset .f function_name
如果你希望直接从终端调用函数,可以将函数定义在主目录下的 .profile 文件,这样每次登录后,在命令提示符后面输入函数名字就可以立即调用。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入因仑

本版积分规则

快速回复 返回顶部 返回列表