unsafe_where_true
unsafe_where_true

Reputation: 6300

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:

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

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.

Upvotes: 1

Views: 1218

Answers (1)

LeGEC
LeGEC

Reputation: 51790

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

Upvotes: 1

Related Questions