你最喜欢在Bash中处理错误的方法是什么?我在网上找到的处理错误的最好例子是由William Shotts,Jr在http://www.linuxcommand.org撰写.
他建议在Bash中使用以下函数进行错误处理:
#!/bin/bash
# A slicker error handling routine
# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run. You can get this
# value from the first item on the command line ($0).
# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>
PROGNAME=$(basename $0)
function error_exit
{
# ----------------------------------------------------------------
# Function for exit due to fatal program error
# Accepts 1 argument:
# string containing descriptive error message …
Run Code Online (Sandbox Code Playgroud) 我想在Bash脚本中引发错误,消息"Test cases Failed !!!".在Bash中如何做到这一点?
例如:
if [ condition ]; then
raise error "Test cases failed !!!"
fi
Run Code Online (Sandbox Code Playgroud) 有没有像linux try catch一样的linux bash命令?或者linux shell总是继续?
try {
`executeCommandWhichCanFail`
mv output
} catch {
mv log
} finally {
rm tmp
}
Run Code Online (Sandbox Code Playgroud) 我正在从php中的普通mysql切换到PDO,我注意到测试错误的常用方法是使用try/catch组合而不是if/else组合.
该方法的优点是什么,我可以使用一个try/catch块而不是几个嵌套的if/else块来处理不同步骤(连接,准备,执行等)的所有错误吗?
给我一些你的想法,哪个是更好的编码实践/使更高效的代码/看起来更漂亮/更好:增加和提高你使用if语句预测和捕捉潜在问题的能力?或者只是简单地使用try/catch?
让我们说这是Java(如果重要的话).
编辑: 我现在正在将自己从一些公认的过时和受限制的当前编码实践中转移出来,但我对于在某些方面(例如这一点)这样做的必要性有点扯淡.我只想问一些观点.不是辩论.
我不能这样做(错误:) line 2: [: ==: unary operator expected
:
if [ $(echo "") == "" ]
then
echo "Success!"
fi
Run Code Online (Sandbox Code Playgroud)
但这很好用:
tmp=$(echo "")
if [ "$tmp" == "" ]
then
echo "Success!"
fi
Run Code Online (Sandbox Code Playgroud)
为什么?
是否可以在if语句中获取命令的结果?
我想做这样的事情:
if [ $(echo "foo") == "foo" ]
then
echo "Success!"
fi
Run Code Online (Sandbox Code Playgroud)
我目前使用这种解决方法:
tmp=$(echo "foo")
if [ "$tmp" == "foo" ]
then
echo "Success!"
fi
Run Code Online (Sandbox Code Playgroud)