创建函数
有两种格式可以用来在 bash shell 脚本中创建函数。
第一种格式采用关键字 function,后跟分配给该代码块的函数名。
function name {
commands
}
name 属性定义了赋予函数的唯一名称。脚本中定义的每个函数都必须有一个唯一的名称。
commands 是构成函数的一条或多条 bash shell 命令。在调用该函数时,bash shell 会按命令在函数中出现的顺序依次执行,就行在普通脚本中一样。
在 bash shell 脚本中定义函数的第二种格式更接近于其他编程语言中定义函数的方式。
name() {
commands
}
使用函数
test1.sh
#!/bin/bash
#using a function in a script
func1() {
echo "This is an example of a function"
}
count=1
while [ $count -le 5 ]
do
func1
count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func1
echo "Now this is the end of the script"
运行结果:
mary@DESKTOP-2PJF7EM:~/mine/learning$ ./test1.sh
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
This is an example of a function
Now this is the end of the script
返回值
默认退出状态码
默认情况下,函数的退出状态码是函数中最后一条命令返回的退出状态码。