bash 如何在 shell 脚本中捕获 Gradle 退出代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42514350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:50:21  来源:igfitidea点击:

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

bashshellgradleexit-code

提问by JJD

I would like to capture the return codeof a Gradle task. Here is a small bash script draftwhich executes a tasks:

我想捕获Gradle 任务的返回代码。这是一个执行任务的小型 bash 脚本草案

#!/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 notstore 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.

请注意,示例脚本是我需要捕获返回值的更复杂脚本的简化。

回答by Charles Duffy

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):

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

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: ifstatements 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:

但是,您根本不需要在此处捕获它:ifshell 中的语句对它们所包含的命令的退出状态进行操作,因此您无需放置检查捕获的退出状态的测试操作,而只需将命令本身放入您的命令部分if

if ./gradlew assembleDebug; then
  echo "Gradle task succeeded" >&2
else
  echo "Gradle task failed" >&2
fi