How to capture the Gradle exit code in a shell scr

2020-06-04 00:50发布

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条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-04 01:10

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
查看更多
登录 后发表回答