Updating local git refs the fast way

When I want to check out a local branch, it quite often happens that its corresponding remote tracking branch had updates by other people, while I didn’t make any changes to the branch.
So in this case I’m not interested in the current state of my my_branch and I just want to obtain and checkout the remote state of my_branch.

Normally, to obtain these remote changes, you would probably run

git checkout my_branch
git pull

In this scenario however, this has one downside: you’re checking out a working directory that you’re not interested in, namely the old state of my_branch.
This is a waste of time, especially when the repositories you’re dealing with are large. What we actually want to do is move the local branch pointer before checking it out.
The following custom git command takes care of that.

update = "!f() { if [ $# -eq 0 ] ; then git reset --hard @{u}; else git fetch . "origin/$1:$1" --recurse-submodules=no; fi }; f"

Now you can run

git update my_branch
git checkout my_branch

and it will not do any superfluous check outs. Moreover, if you are already on my_branch, you can run git update to explicitly move the branch pointer, instead of git merge.

Leave a Reply

Your email address will not be published. Required fields are marked *