此示例在 Mac El Capitan 上使用 bash 进行了测试
main_script.sh:
注意: func_a 和 func_b 是相同的,除了
output
声明局部变量的那一行。
func_a () {
local output
output="$(./external.sh some_function)"
if [ $? -eq 0 ];then
echo "A zero result ($?) -> $output <- end"
else
echo "A other result ($?) -> $output <- end"
fi
}
func_b () {
local output="$(./external.sh some_function)"
if [ $? -eq 0 ];then
echo "B zero result ($?) -> $output <- end"
else
echo "B other result ($?) -> $output <- end"
fi
}
func_a
func_b
外部.sh:
some_function () {
echo "this is the output"
return 1
}
"$@"
当我运行 main_script 时,输出是:
A other result (1) -> this is the output <- end
B zero result (0) -> this is the output <- end
出于什么原因,在与命令替换相同的行上声明局部变量会影响结果?这可能是一个错误还是我错过了什么?