mirk
mirk

Reputation: 5510

check out a git branch programmatically in a script

I would like to check out the latest state of a remote git branch in a script for some integration-tests.

The branch name can be changed by the programmer in between runs. I would like git not to fully clone the whole repository each time in order not to lose too much time.

Since the script gets run regularly on an existing repo, the branch can already exist locally.

I have a hard time getting the commands right. The solution below fails to pull when a remote (unrelated branch) is deleted.

         if cd $builddir ;
            then git fetch origin $gitbranch &&  git checkout --track $gitbranch ; git pull
            else git clone --branch $gitbranch $gitrepo $builddir;
         fi

Is there an elegant solution for this? I am using git 1.7.1 on Centos 6.5.

Upvotes: 2

Views: 1028

Answers (2)

Kousha
Kousha

Reputation: 1625

You can try to delete stale remote refs:

git remote prune origin

Upvotes: 1

VonC
VonC

Reputation: 1323503

Considering an older instance of the script could have checked out a branch now deleted on the remote side, I would first remove any local config branch setting:

git config --remove-section branch.old_branch

(you can iterate on all local branches, with, for instance, a for-each)

Then, I would try to fetch/clone

That would avoid the error message:

Your configuration specifies to rebase against the ref '`old_branch`' from the remote, but no such ref was fetched.

Upvotes: 1

Related Questions