函数的定义
在Shell中可以通过下面的两种语法来定义函数,分别如下:
- function_name ()
- {
- statement1
- statement2
- ....
- statementn
- }
或者
- function function_name()
- {
- statement1
- statement2
- ....
- statementn
- }
函数的调用
当某个函数定义好了以后,用户就可以通过函数名来调用该函数了。在Shell中,函数调用的基本语法如下,
- function_name parm1 parm2
下面定义了一个 sayhell()的方法,并调用
- #! /bin/bash
- function sayhello()
- {
- echo "Hello,World"
- }
- sayhello
代码调用结果
- [root@VM_156_149_centos shell]# sh hello.sh
- Hello,World
函数的返回值
首先,用户利用return来返回某个数值,这个与绝大部分的程序设计语言是相同的。但是在Shell中,return语句只能返回某个0-255之间的整数值。在Shell中还有一种更优雅的方法帮助用户来获得函数执行后的某个结果,那就是使用echo。在函数中,用户需要将要返回的数据写入到标准输出(stout),通常这个操作是使用echo语句来完成的,然后在调用程序中将函数的执行结果赋值给一个变量。这种做法实际上就是一个命令替换的一个变种。
函数使用return返回值
函数的定义@H_301_40@
- #! /bin/bash
-
- function sum()
- {
- returnValue=$(( $1 + $2 ))
- return $returnValue
- }
-
- sum 22 4
-
- echo $?
- #! /bin/bash
- function sum()
- {
- returnValue=$(( $1 + $2 ))
- return $returnValue
- }
- sum 22 4
- echo $?
函数的调用@H_301_40@
- [root@VM_156_149_centos shell]# sh sum.sh
- 26
- [root@VM_156_149_centos shell]# sh sum.sh
- 26
函数返回值大于0-255,出错的情况@H_301_40@
在上面的执行结果可以看到,所传递的两个数的和被成功的返回。但是通过return只能返回整数值,并且是0-255的范围,如果超出这个范围就会错误的结果。例如将上面的代码换成下面的参数
- sum 253 4
则执行结果如下,
- [root@VM_156_149_centos shell]# sh sum.sh
- 1
可以发现,正确的结果应该是257,但是函数的返回值是1.
函数使用echo返回值
函数的定义@H_301_40@
- #! /bin/bash
-
- function length()
- {
- str=$1
- result=0
- if [ "$str" != "" ] ; then
- result=${#str}
- fi
- echo "$result"
- }
-
- len=$(length "abc123")
-
- echo "The string's length is $len "
- #! /bin/bash
- function length()
- {
- str=$1
- result=0
- if [ "$str" != "" ] ; then
- result=${#str}
- fi
- echo "$result"
- }
- len=$(length "abc123")
- echo "The string's length is $len "
函数的调用@H_301_40@
- [root@VM_156_149_centos shell]# sh length.sh
- The string's length is 6
- [root@VM_156_149_centos shell]# sh length.sh
- The string's length is 6