Shell函数的使用

2017-05-18  本文已影响0人  qianghaohao

shell中的函数和其他语言的函数类似,也有参数和返回值。
shell中的函数声明格式如下:

function fname() {
    函数体
}

举例如下:

#########################################################################
# File Name: print_hello_world.sh
# Author: haohao.qiang
# mail: codenutter@foxmail.com
# Created Time: 四  5/18 13:37:23 2017
#########################################################################
#!/bin/bash
function print_hello_world() {  # 函数定义
   echo "hello, world!"
}

print_hello_world   #调用上面定义的函数

执行结果如下:

➜  ~ git:(develop) ✗ sh print_hello_world.sh 
hello, world!
#########################################################################
# File Name: function_demo.sh
# Author: haohao.qiang
# mail: codenutter@foxmail.com
# Created Time: 四  5/18 12:55:19 2017
#########################################################################
#!/bin/bash
# 求两个数的和
function add() {
  let result=$1+$2
  return $result
}

# 调用函数求和,参数为30 20
add 30 20
# $? 为函数的返回值,默认函数返回值为函数体中最后一条语句的返回值
echo $?

执行结果如下:

➜  ~ git:(develop) ✗ sh function_demo.sh 
50
上一篇 下一篇

猜你喜欢

热点阅读