Shell 函数

在开始编写复杂的shell脚本时,有时候你会发现在编写很多重复的代码。bash shell支持用户定义的函数。可以将shell脚本的代码进行封装。方便以后多次使用和维护。

有两种方式可以创建bash shell的函数:
方式一:采用关键字function,后面跟着函数名称。例如:

#!/bin/bash

function hello {
	echo This is hello function.
}

hello

输出结果:
This is hello function.

 注意: 方法与后面的大括号要有空格,不可以写成 Hello{  这样是错误的。

方式二:不实用function关键字。直接是方法的名字。例如:

#!/bin/bash

hello() {
	echo This is hello function.
}

hello

输出结果:
This is hello function.

第二种方法,函数名和后面的小括号和大括号可以有空格也可以没有。不过建议在大括号写一个空格。

注意:再调用函数的时候,函数定义必须在调用之前定义。
如果在同一个shell中重复定义了一个函数,不会产生任何错误。后续使用该函数,都会使用第二个定义的函数。例如:

#!/bin/bash

hello() {
	echo This is hello function.
}

hello

hello() {
	echo This is a repeat of the hello function.
}

hello

输出结果:
This is hello function.
This is a repeat of the hello function.

这只是简单的函数,没有参数,没有返回值。
继续研究一下bash shell 如何获取函数退出状态码。可以说有三种返回值:
方式一:
默认状态下,函数的退出状态码是函数中执行最后一条命令的退出状态码,可以用$?获取状态码。例如:

testReturn() {
	echo Hello
}

testReturn

echo The exit status is $?

输出结果:
0

方式二:使用return。return命令允许指定一个数值作为函数的退出状态码。

testReturn() {
	return 10
}

testReturn
echo The exit status is $?

输出结果:10
注意:退出状态码必须在0-255之间。要是返回较大的数值或者字符串,必须使用下面的方法了。

方法三:将函数的输出保存到shell变量中。

#!/bin/bash

testReturn() {
	echo Hello
}

RESULT=`testReturn`
echo $RESULT

输出结果:Hello

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>