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

让人想犯罪 __ 提交于 2020-01-31 09:03:04

问题


I would like to capture the return code of a Gradle task. Here is a small bash script draft which executes a tasks:

#!/bin/bash

gradlew_return_code=`./gradlew assembleDebug`
echo ">>> $gradlew_return_code"
if [ "$gradlew_return_code" -eq "0" ]; then
    echo "Gradle task succeeded."
else
    echo "Gradle task failed."
fi

The script does not store the return value but instead the whole console output of the Gradle task.


Please note that the example script is a simplification of a more complex script where I need to capture the return value.


回答1:


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


来源:https://stackoverflow.com/questions/42514350/how-to-capture-the-gradle-exit-code-in-a-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!