我发现我的脚本使用这种语法是成功的:
# Try, catch, finally
(echo "try this") && (echo "and this") || echo "this is the catch statement!"
# this is the 'finally' statement
echo "finally this"
如果任一 try 语句抛出错误或以 exit 1 结尾,则解释器将继续执行 catch 语句,然后是 finally 语句。
如果两个 try 语句都成功(和/或以 exit 结束),解释器将跳过 catch 语句,然后运行 finally 语句。
示例_1:
goodFunction1(){
# this function works great
echo "success1"
}
goodFunction2(){
# this function works great
echo "success2"
exit
}
(goodFunction1) && (goodFunction2) || echo "Oops, that didn't work!"
echo "Now this happens!"
输出_1
success1
success2
Now this happens!
示例_2
functionThrowsErr(){
# this function returns an error
ech "halp meh"
}
goodFunction2(){
# this function works great
echo "success2"
exit
}
(functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"
echo "Now this happens!"
输出_2
main.sh: line 3: ech: command not found
Oops, that didn't work!
Now this happens!
示例_3
functionThrowsErr(){
# this function returns an error
echo "halp meh"
exit 1
}
goodFunction2(){
# this function works great
echo "success2"
}
(functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"
echo "Now this happens!"
输出_3
halp meh
Oops, that didn't work!
Now this happens!
请注意,函数的顺序会影响输出。如果您需要分别尝试和捕获两个语句,请使用两个 try catch 语句。
(functionThrowsErr) || echo "Oops, functionThrowsErr didn't work!"
(goodFunction2) || echo "Oops, good function is bad"
echo "Now this happens!"
输出
halp meh
Oops, functionThrowsErr didn't work!
success2
Now this happens!