Search code examples
gitgit-branchgit-checkoutgit-repo

Unequivocally checkout a branch and get latest version in git from a script


I am creating a shell build script.

I want it to be called like this:

./build.sh REPONAME BRANCHNAME

$REPONAME corresponds to a remote. I am assuming that the remote exists. $BRANCHNAME is a branch existing on $REPONAME.

$BRANCHNAME may have never been checked out on this computer.

So I have this:

cd $REPOPATH
git fetch $REPONAME $BRANCHNAME
git checkout --track $REMOTE/$BRANCHNAME
git pull $REPONAME
echo `git rev-parse HEAD`

This kind of works but I am experiencing several issues:

  • I have to enter my key's private key twice - I guess once for fetch and once for pull. Not critical but if it would be just once, would be better.
  • Because of --track, if $BRANCHNAME was already checked out in the past, I get

fatal: A branch named $BRANCHNAME already exists

. No idea how fatal that really is but I don't like to see a fatal in the output

  • Without the --track, I get into detached mode, which I also do not like
  • With just git checkout $BRANCHNAME I was suddenly getting messages about "ambiguous" branches. Maybe because $BRANCHNAME could be on several remotes?

So what is the cleanest and unequivocal way to checkout a branch from a remote, get its latest version and build from it?f

It's astonishing how after so many years using git I still don't have a grasp of what feels like must-know skills.


Solution

  • If you want to discard everything and get the remote version :

    git fetch $REMOTE
    git stash
    git checkout $BRANCHNAME
    git branch -u $REMOTE/$BRANCHNAME
    git reset --hard $REMOTE/$BRANCHNAME
    

    If you want to merge the updates from the remote branch in your local branch :

    git fetch $REMOTE
    git stash
    git checkout $BRANCHNAME
    git branch -u $REMOTE/$BRANCHNAME
    git merge $REMOTE/$BRANCHNAME