Update Local Git Branches Without Switching

 
 
  • Gérald Barré

When you need to switch to a branch that is behind the remote, the typical workflow involves switching to it and then pulling the latest changes. This process can be disruptive when your IDE reloads the project on every branch switch.

Shell
git switch main # Switch branch   (IDE reload #1)
git pull        # Fetch and merge (IDE reload #2)

Git allows you to update a local branch without leaving your current workspace. Use git fetch with a refspec that directly updates your local branch:

Shell
git fetch origin main:main # Update local main with remote changes (no IDE reload)
git switch main            # Now switch to main (IDE reload #1)

This fetches the latest main from origin and updates your local main directly, without switching to it first.

The IDE will not reload the project since no branch switch occurs. This is especially useful for large projects where reloads take considerable time.

This technique has one constraint: it only works for fast-forward updates, meaning your local branch must be behind the remote with no conflicting local commits.

If you have local commits on the target branch that you want to discard, use the + prefix to force the update:

Shell
git fetch origin +main:main  # The + forces non-fast-forward

You can also use git branch --force or git update-ref for the same result, though these methods are less commonly used.

#Using git branch -f (Force Update)

Shell
# First fetch the latest refs
git fetch origin
# Then force update the branch pointer
git branch --force main origin/main

#Using git update-ref (Low-Level Update)

Shell
# Fetch latest and get the commit hash
git fetch origin
COMMIT_HASH=$(git rev-parse origin/main)
# Update the branch reference directly
git update-ref refs/heads/main $COMMIT_HASH

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?