我正在编写一些BASH脚本,我希望它有一些错误处理机制:
function f()
{
command1 || { echo "command1 failed"; return 1; }
command2 || { echo "command2 failed"; return 1; }
command3 || { echo "command3 failed"; return 1; }
command4 || { echo "command4 failed"; return 1; }
}
我想通过定义一些函数来使这个重复结构更具可读性:
function print_and_return()
{
echo "$@"
# some way to exit the caller function
}
这样我就可以将函数f
写成
function f()
{
command1 || print_and_return "command1 failed"
command2 || print_and_return "command2 failed"
command3 || print_and_return "command3 failed"
command4 || print_and_return "command4 failed"
}
实现这一目标的最佳方法是什么?感谢。
答案 0 :(得分:2)
你想要:
您可以重构代码。例如:
print_and_return() {
echo "command failed: $@" >&2
return 1
}
commands=("cmd1" "cmd2" "cmd3" "cmd4")
for cmd in "${commands[@]}"; do
{ $cmd || print_and_return "$cmd"; } || break
done
答案 1 :(得分:1)
也许你可以使用set -e
,但是你必须小心,因为它退出了shell:
function f()
{
(
set -e
command1
command2
command3
command4
)
}
只要命令诊断出任何问题,当第一个命令失败时,此函数将停止。
测试版本:
function f()
{
(
set -e
true
echo true
true
echo true
false
echo false
true
echo true
)
}
echo calling function
f
echo still here
输出:
calling function
true
true
still here
注意:当我使用序列时:
echo calling function
if f
then echo still here - f passed
else echo still here - f failed
fi
然后在Mac OS X 10.7.4上的bash 3.2.48下该函数表现不同:
calling function
true
true
false
true
still here - f passed
所以,有创造力,但并非完全可靠。
答案 2 :(得分:0)
与CodeGnome's solution类似,但不使用数组(可能不会出现在每个shell中):
function callthem()
{
for cmd; do # short form for "for cmd in "$@"; do"
"$cmd" || { echo "$cmd failed." >&2; return 1; }
done
}
function f()
{
callthem command1 command2 command3 command4
# or maybe even
callthem command{1,2,3,4}
}