How can I get the current git branch in gradle?

I’m writing a task to deploy my application to the server. However, I’d like for this task to run only if my current git branch is the master branch.
How can I get the current git branch?

gradle-git approach:

I know there is a gradle-git plugin that has a method getWorkingBranch() under the task GitBranchList, but anytime I try to execute

  • Local git repository using window 7 with XAMPP server
  • Git: Needed a single revision error
  • Connect to Bitbucket Git SSH Public Key
  • What's the difference between `git config` and `git push --set-upstream`
  • Config default Git branch name
  • RTC - Is it possible to have personal repo for each-user like Git provides
  • task getBranchName(type: GitBranchList) {
       print getWorkingBranch().name

    I get a “Task has not executed yet” error. I looked at the source and it throws that error when there is no branch set. Does that mean this method doesn’t do quite what I think it does? That I need to set the branch somewhere?

  • git revert - git asking parent1 or parent2
  • Git: Change timestamp after pushing
  • bypass pre-commit hook for merge commits
  • How do I delete other subdirectories when doing git filter-branch
  • Run git pull over all subdirectories
  • GIT: Get Bash Here on network location
  • 2 Solutions collect form web for “How can I get the current git branch in gradle?”

    No this doesn’t mean that the branch is not set. It means that the task hasn’t really executed yet. What you’re trying to do is calling a method in the configuration closure, whereas you probably want to call it after task execution. Try to change your task to:

    task getBranchName(type: GitBranchList) << {
        print getWorkingBranch().name

    With the << you’re adding a doLast, which will be executed after the task has been executed.

    You also are able to get git branch name without the plug-in.

    def gitBranch() {
        def branch = ""
        def proc = "git rev-parse --abbrev-ref HEAD".execute() { line -> branch = line }
        proc.err.eachLine { line -> println line }

    Refer to: Gradle & GIT : How to map your branch to a deployment profile

    Git Baby is a git and github fan, let's start git clone.