Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 213
JJD Avatar asked Feb 28 '17 16:02

JJD


1 Answers

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
like image 113
Charles Duffy Avatar answered Sep 20 '22 11:09

Charles Duffy