smi*_*lli 5 bash shell-script function exit error-handling
假设我有以下(毫无意义的)Bash 函数:
myfunc() {
ls
failfailfail
uptime
}
Run Code Online (Sandbox Code Playgroud)
我按如下方式运行它:
myfunc || echo "Something is wrong."
Run Code Online (Sandbox Code Playgroud)
我想要发生的是ls
运行(因为它应该),failfailfail
不起作用(因为它不存在),并且uptime
不运行。该函数的返回值将是非零的,并且将显示错误消息。返回值不必是失败命令的确切退出状态,它不应该为零。
而实际上,我得到的输出ls
,其次是“-bash:failfailfail:未找到命令”,然后输出uptime
。错误消息未显示,因为失败的退出状态正在被吃掉。
set -e
无论是在函数内还是在调用函数的作用域内,都没有任何有用的效果。我可以让它按照我想要的方式工作的唯一方法是:
myfunc() {
ls || return $?
failfailfail || return $?
uptime || return $?
}
Run Code Online (Sandbox Code Playgroud)
但这似乎非常重复和丑陋。有没有另一种方法来清理它?
使它更简单的唯一方法是将其全部组合在一个命令中,但这使得脚本比上一个版本更难维护:
myfunc() {
ls && failfailfail && uptime || return $?
}
Run Code Online (Sandbox Code Playgroud)