Bash函数:返回值、变量使用与递归应用
在Bash脚本编程中,函数是非常实用的工具,它可以将一段代码封装起来,方便重复使用。下面将详细介绍Bash函数的返回值、变量使用、数组操作、递归以及库的创建等方面的内容。
函数返回值
Bash shell将函数视为小型脚本,函数有退出状态。生成函数退出状态有三种不同的方式。
- 默认退出状态 :默认情况下,函数的退出状态是函数中最后一个命令的退出状态。可以使用标准的 $? 变量来确定函数的退出状态。
$ cat test4
#!/bin/bash
# testing the exit status of a function
func1() {
echo "trying to display a non-existent file"
ls -l badfile
}
echo "testing the function: "
func1
echo "The exit status is: $?"
$
$ ./test4
testing the function:
trying to display a non-existent file
ls: badfile: No such file or directory
The exit status is: 1
$
在这个例子中,函数的退出状态是1,因为函数中的最后一个命令 ls -l badfile 失败了。不过,使用默认退出状态无法知道函数中其他命令是否成功执行。
超级会员免费看
订阅专栏 解锁全文
705

被折叠的 条评论
为什么被折叠?



