如何在Shell脚本中捕获Gradle退出代码? [英] How to capture the Gradle exit code in a shell script?

查看:189
本文介绍了如何在Shell脚本中捕获Gradle退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获Gradle任务的返回代码.这是一个小的bash脚本草稿,它执行任务:

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

该脚本不会存储返回值,而是存储Gradle任务的整个控制台输出.

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.

推荐答案

退出状态为$?.命令替换捕获输出.

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

./gradlew assembleDebug; gradlew_return_code=$?

...或者,如果您需要与set -e兼容(我强烈建议不要使用 ):

...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.

但是,您根本不需要在这里捕获它:if shell中的语句对它们所包含的命令的退出状态进行操作,因此,您不必进行检查已捕获的退出状态的测试操作,而只需执行以下操作即可:将命令本身放在if的COMMAND部分:

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

这篇关于如何在Shell脚本中捕获Gradle退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆