函数返回值
在默认情况下,函数的退出状态码是函数中最后一个命令返回的退出状态码。函数执行结束
后,可以使用标准变量$?来确定函数的退出状态码:
$ 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,因为函数中的最后一个命令执行失败了。但你无法知道该函数中
的其他命令是否执行成功。来看下面的例子:
$ cat test4b
#!/bin/bash
# testing the exit status of a function
func1() {
ls -l badfile
echo "This was a test of a bad command"
}
echo "testing the function:"
func1
echo "The exit status is: $?"
$
$ ./test4b
testing the function:
ls: badfile: No such file or directory
This was a test of a bad command
The exit status is: 0
$