从 bash 中的 build.gradle 读取 versionName

Read versionName from build.gradle in bash

有没有办法从 Android 项目的 build.gradle 文件中读取值 versionName 以在 bash 中使用它?

更准确地说:如何从文件中读取这个值并在 Travis-CI 脚本中使用它?我会像

一样使用它
# ANDROID_VERSION=???
export GIT_TAG=build-$ANDROID_VERSION

我按照 post .

中所述设置了 Travis-CI

我的build.gradle:http://pastebin.com/uiJ0LCSk

例如

android{
  android.applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def outputFile = output.outputFile
        def fileName
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
            if (!outputFile.name.contains('unaligned')) {
                fileName = "yourAppRootName_${variant.productFlavors[0].name}_${getVersionName()}_${variant.buildType.name}.apk"
                output.outputFile = new File(outputFile.parent + "/aligned", fileName)
            }
        }
    }
}
}

使用${getVersionName()}获取build.gradle中的版本

感谢 comment I came up with this solution (note ):

# variables
export GRADLE_PATH=./app/build.gradle   # path to the gradle file
export GRADLE_FIELD="versionName"   # field name
# logic
export VERSION_TMP=$(grep $GRADLE_FIELD $GRADLE_PATH | awk '{print }')    # get value versionName"0.1.0"
export VERSION=$(echo $VERSION_TMP | sed -e 's/^"//'  -e 's/"$//')  # remove quotes 0.1.0
export GIT_TAG=$TRAVIS_BRANCH-$VERSION.$TRAVIS_BUILD_NUMBER
# result
echo gradle version: $VERSION
echo release tag: $GIT_TAG

您可以自定义任务,即

task printVersion {
    doLast {
        println project.version
    }
}

并在Bash中执行:

$ gradle -q pV
1.8.5

扩展 Khozzy 的回答,从 build.gradle 中检索 Android 包的版本名称,添加此自定义任务:

task printVersionName {
    doLast {
        println android.defaultConfig.versionName
    }
}

并这样调用它:

gradle -q printVersionName

这个怎么样?

grep -o "versionCode\s\+\d\+" app/build.gradle | awk '{ print  }'

-o 选项使 grep 只打印匹配的部分,因此可以保证传递给 awk 的只是模式 versionCode NUMBER.

如果您正在寻找 Kotlin DSL 的迁移版本,这里是我想出的:

tasks.create("printVersionName") {
    doLast { println(version) }
}

如果你有多个flavor并且在flavor中设置了版本信息,你可以这样使用:

task printVersion{
doLast {
    android.productFlavors.all {
        flavor ->
            if (flavorName.matches(flavor.name)) {
                print flavor.versionName + "-" + flavor.versionCode
            }
    }
}
}

然后您可以使用

调用它
./gradlew -q printVersion -PflavorName=MyFlavor

我喜欢这一行,只获取不带引号的版本名称:

grep "versionName" app/build.gradle | awk '{print }' | tr -d \''"\'

grep 版本名称:

对于MAC

grep -o "versionName\s.*\d.\d.\d" app/build.gradle | awk '{ print }' | tr -d \''"\'

对于 Unbuntu :

grep -o "versionName\s\+.*" app/build.gradle | awk '{ print }' | tr -d \''"\'

所以输入build.gradleversionName "8.1.9"给我8.1.9