我正在提交一个预先提交脚本。它看起来像这样:如何在出错时退出bash功能?
function presubmit() {
gradle test android
gradle test ios
gradle test server
git push origin master
}
我想要函数退出,如果任何测试失败,所以它不会推动bug到git。怎么样?
我正在提交一个预先提交脚本。它看起来像这样:如何在出错时退出bash功能?
function presubmit() {
gradle test android
gradle test ios
gradle test server
git push origin master
}
我想要函数退出,如果任何测试失败,所以它不会推动bug到git。怎么样?
通常当我调用一个函数,并希望错误消息柜面失败我这样做:
presubmit || { echo 'presubmit failed' ; exit 1; }
通过添加||
标志,它将决定表达式是否为true。
希望这有助于:)
在'git push'执行之前,OP希望'presubmit'提前退出。这只是显示如何做一些额外的'presubmit'退出与非零退出状态。 – chepner
你可以这样做:
# declare a wrapper function for gradle
gradle() {
command gradle "[email protected]" || exit 1
}
presubmit() {
gradle test android
gradle test ios
gradle test server
git push origin master
}
declare -xf presubmit gradle
调用该函数在子shell为:
(presubmit)
使用内置set -e
:
#!/bin/bash
set -e
# Any subsequent commands which fail will cause the shell script to exit immediately
从set -e
文档文本:
-e:立即如果pipeline退出,这可以由单个simple command,一个list,或者compound command的返回一个非零状态。如果失败的命令是命令列表的一部分,紧接着一段时间或直到关键字,if语句中的测试的一部分,在& &或||中执行的任何命令的一部分,shell不会退出。除了最后的命令& &或||之外的命令,除了最后一个流水线中的任何命令外,或者命令的返回状态与!相反。如果由于命令在-e被忽略时失败而导致子shell以外的复合命令返回非零状态,则shell不会退出。如果设置了ERR,则会在shell退出之前执行陷阱。
此选项单独应用于shell环境和每个子shell环境(请参阅Command Execution Environment),并且可能会导致子shell在执行子shell中的所有命令之前退出。
如果复合命令或shell函数在忽略-e的上下文中执行,则在-e设置时,复合命令或函数体内执行的任何命令都不会受到-e设置的影响,并且一个命令返回一个失败状态。如果复合命令或shell函数在忽略-e的上下文中执行时设置-e,那么在复合命令或包含函数调用的命令完成之前,该设置将不起作用。
当函数*中的某些内容失败时,这不起作用。 – bviktor
我会做脚本的详细粒:
#!/bin/bash
function test() {
gradle test android
gradle test ios
gradle test server
}
function push() {
git push origin master
}
# this subshell runs similar to try/catch
(
# this flag will make to exit from current subshell on any error inside test or push
set -e
test
push
)
# you catch errors with this if
if [ $? -ne 0 ]; then
echo "We have error"
exit $?
fi
我们只有内部测试和推跟踪误差。您可以在测试和推送运行的子shell之外添加更多操作。您也可以通过这种方式为错误添加不同的范围(让我们将其视为try/catch)
http://www.tldp。组织/ LDP/ABS/HTML /出口status.html –
你可以看看[这](http://stackoverflow.com/questions/30078281/raise-error-in-bash-script/30078353#30078353) – ForceBru
'gradle ... || return'? – Cyrus