你把两件事混为一谈了:
输出
和
退出状态
.
echo
产生
输出
. 命令替换,如
$(...)
捕获该输出,但如果在没有它的情况下运行命令,则该输出将转到终端。
return
套
退出状态
. 这是用来确定在运行时执行哪个分支的
if your_function; then ...
,或填充
$?
.
去看看你的
return_test
实际上,你可以写下:
return_test() {
return 1;
}
return_test; echo "Exit status is $?"
另外,请注意,可以同时执行以下两种操作:
myfunc() {
echo "This is output"
return 3
}
myfunc_out=$(myfunc); myfunc_rc=$?
echo "myfunc_out is: $myfunc_out"
echo "myfunc_rc is: $myfunc_rc"
…发射:
myfunc_out is: This is output
myfunc_rc is: 3
一个有用的习惯用法是把作业放在
if
条件,在捕获输出时分支到退出状态:
if myfunc_out=$(myfunc); then
echo "myfunc succeeded (returned 0), with output: [$myfunc_out]"
else rc=$?
echo "myfunc failed (nonzero return of $rc), with output: [$myfunc_out]"
fi
……在这种情况下,它将返回:
myfunc failed (nonzero return of 3), with output: [This is output]
顺便说一下,您可能会注意到,当上面的代码捕获
$?
它尽可能地接近正在捕获其退出状态的命令,即使这意味着打破垂直空格周围的常规约定。这是有意的,目的是降低无意中修改添加日志或其他代码更改的可能性
$?
在设定点和使用点之间。