Dam
Dam

Reputation: 41

How to echo the current git branch in my Travis Build

I am unable to get branch in travis build. If I do echo $(git branch) in the script and run it in Travis. It echoes (HEAD detached at 82abe25) master

Is there anyway, I can just get the branch name? I emphasize it is in Travis.

I also tried git symbolic-ref --short HEAD but in vain.

Upvotes: 0

Views: 1125

Answers (1)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

You can get the name of the branch being built by reading the TRAVIS_BRANCH environment variable.

From the documentation:

TRAVIS_BRANCH:

  • for push builds, or builds not triggered by a pull request, this is the name of the branch.
  • for builds triggered by a pull request this is the name of the branch targeted by the pull request.
  • for builds triggered by a tag, this is the same as the name of the tag (TRAVIS_TAG).

Reading your comment, I understand you want to run the same script in Jenkins, as well. Most CI servers will check out a specific commit when running a build (i.e. a detached HEAD), so you won't be able to use Git to determine which branch you're on.

You're better off just checking for different environment variables in your script:

if [[ -v $TRAVIS_BRANCH ]]; then
    branch=$TRAVIS_BRANCH
elif [[ -v $GIT_BRANCH ]]; then
    branch=$GIT_BRANCH
fi

Upvotes: 1

Related Questions