How to capture the Gradle exit code in a shell script?

感情迁移 提交于 2019-12-03 13:41:15

Exit status is in $?. Command substitutions capture output.

./gradlew assembleDebug; gradlew_return_code=$?

...or, if you need compatibility with set -e (which I strongly advise against using):

gradlew_return_code=0
./gradlew assembleDebug || gradlew_return_code=$?

...or, if you need to capture both:

gradlew_output=$(./gradlew assembleDebug); gradlew_return_code=$?
if (( gradlew_return_code != 0 )); then
  echo "Grade failed with exit status $gradlew_return_code" >&2
  echo "and output: $gradlew_output" >&2
fi

Note that I do advise putting the capture on the same line as the invocation -- this avoids modifications such as added debug commands from modifying the return code before capture.


However, you don't need to capture it at all here: if statements in shell operate on the exit status of the command they enclose, so instead of putting a test operation that inspects captured exit status, you can just put the command itself in the COMMAND section of your if:

if ./gradlew assembleDebug; then
  echo "Gradle task succeeded" >&2
else
  echo "Gradle task failed" >&2
fi
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!