Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read versionName from build.gradle in bash

Is there a way to read the value versionName from the build.gradle file of an Android project to use it in bash?

More precisely: How can I read this value from the file and use it in a Travis-CI script? I'll use it like

# ANDROID_VERSION=???
export GIT_TAG=build-$ANDROID_VERSION

I set up a Travis-CI like described in this post https://stackoverflow.com/a/28230711/1700776.

My build.gradle: http://pastebin.com/uiJ0LCSk

like image 936
SUhrmann Avatar asked Feb 18 '16 07:02

SUhrmann


4 Answers

Expanding on Khozzy's answer, to retrieve versionName of your Android package from the build.gradle, add this custom task:

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

and invoke it so:

gradle -q printVersionName
like image 115
Alex Suzuki Avatar answered Oct 22 '22 09:10

Alex Suzuki


You can define a custom task, i.e.

task printVersion {
    doLast {
        println project.version
    }
}

And execute it in Bash:

$ gradle -q pV
1.8.5
like image 37
Khozzy Avatar answered Oct 22 '22 08:10

Khozzy


Thanks to alnet's comment I came up with this solution (note Doug Stevenson's objection):

# 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 $2}')    # 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
like image 8
SUhrmann Avatar answered Oct 22 '22 10:10

SUhrmann


How about this?

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

The -o option makes grep only print the matching part so you're guaranteed that what you pass to awk is only the pattern versionCode NUMBER.

like image 7
hasen Avatar answered Oct 22 '22 10:10

hasen