Bash:为什么';返回0';括号中没有';t退出该函数
在下面的bash代码示例中。使用Bash:为什么';返回0';括号中没有';t退出该函数,bash,shell,Bash,Shell,在下面的bash代码示例中。使用0调用函数时,我希望返回0退出函数。然而,该职能继续向前发展 ignoringReturnStatement(){ local seconds="$1" [[ "$seconds" -eq "0" ]] && (echo "equals 0" && return 0 ) echo "Didn't exit with 'return 0'" return 1 } ignoringReturnStatement 0 &
0
调用函数时,我希望返回0
退出函数。然而,该职能继续向前发展
ignoringReturnStatement(){
local seconds="$1"
[[ "$seconds" -eq "0" ]] && (echo "equals 0" && return 0 )
echo "Didn't exit with 'return 0'"
return 1
}
ignoringReturnStatement 0 && echo "Return code truthy" || echo "Return code falsy"
输出
equals 0
Didn't exit with 'return 0'
Return code falsy
为什么返回0
被忽略?它是否以某种方式被限定在它所在的括号()内?(我习惯于抨击没有做太多的范围界定,这会非常令人惊讶)
如果语法,我可以使用更详细的来重构此代码,使其按预期工作:
respectingReturnStatement(){
local seconds="$1"
if [[ "$seconds" -eq "0" ]]; then
echo "equals 0"
return 0
fi
echo "Didn't exit with 'return 0'"
return 1
}
respectingReturnStatement 0 && echo "Return code truthy" || echo "Return code falsy"
但是为什么&(…返回0)
语法在这里不起作用?它没有被忽略;它在一个地下室中执行。如果它失败了,对我来说并不明显,因为它没有在该shell中的函数中使用,或者如果它从该子shell“返回”到该函数
foo (){
local seconds="$1"
[[ "$seconds" -eq "0" ]] && { echo "equals 0"; return 0; }
echo "Didn't exit with 'return 0'"
return 1
}
要解决此问题,请使用{…}
,而不是(…)
,以便返回
与函数的其余部分在同一shell中执行
foo (){
local seconds="$1"
[[ "$seconds" -eq "0" ]] && { echo "equals 0"; return 0; }
echo "Didn't exit with 'return 0'"
return 1
}
几乎没有理由在上使用&
代码>,因为您希望返回,即使由于某些罕见的原因,echo
失败。它不会被忽略;它在一个地下室中执行。如果它失败了,对我来说并不明显,因为它没有在该shell中的函数中使用,或者如果它从该子shell“返回”到该函数。