有没有像java try catch finally这样的linux bash命令?还是linux shell一直在运行?
try {
`executeCommandWhichCanFail`
mv output
} catch {
mv log
} finally {
rm tmp
}
发布于 2013-03-27 18:29:10
嗯,差不多吧:
{ # your 'try' block
executeCommandWhichCanFail &&
mv output
} || { # your 'catch' block
mv log
}
rm tmp # finally: this will always happen
发布于 2013-11-20 09:32:16
根据您的示例,无论脚本如何退出,您似乎都在尝试执行类似于始终删除临时文件的操作。要在Bash中执行此操作,请尝试trap
内置命令来捕获EXIT
信号。
#!/bin/bash
trap 'rm tmp' EXIT
if executeCommandWhichCanFail; then
mv output
else
mv log
exit 1 #Exit with failure
fi
exit 0 #Exit with success
rm tmp
语句中的trap
始终在脚本退出时执行,因此将始终尝试删除文件"tmp“。
还可以重置已安装的陷阱;调用仅带信号名称的陷阱将重置信号处理程序。
trap EXIT
有关更多详细信息,请参阅bash手册页面:man bash
发布于 2020-03-01 02:31:24
我在我的脚本中成功地使用了以下语法:
# 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!
https://stackoverflow.com/questions/15656492
复制相似问题