How to update a Git branch from another branch
By Flavio Copes
Learn how to update a Git branch with changes from another branch by running git checkout on it, then git merge to pull in the other branch's commits.
To update a Git branch with the changes from another branch, you check out the branch you want to update, then merge the other branch into it.
I ran into this while working on a branch that was not up to date with changes I was doing on another branch. So, I had to incorporate those changes.
You checkout the branch you want to update:
git checkout my-branch
and you merge from the branch you want to update from:
git merge another-branch
That’s it. my-branch now contains all the commits from another-branch, plus its own.
What does the merge actually do?
If my-branch has no commits of its own since the branches diverged, Git performs a fast-forward: it just moves the branch pointer ahead. The output says Fast-forward and no new commit is created.
If both branches have their own commits, Git creates a merge commit that ties the two histories together. An editor opens with a default message like Merge branch 'another-branch' into my-branch. Save and close it, and you’re done.
Either way, another-branch itself is untouched. Merging copies changes in one direction only.
Make sure the other branch is current
Be careful with one thing: git merge another-branch merges your local copy of that branch. If a teammate pushed new commits to it, your local copy is stale and you’ll merge outdated work without any warning.
Download the latest state first:
git fetch origin
git merge origin/another-branch
Merging origin/another-branch uses what’s actually on the remote, not whatever your local branch last saw.
What if there are conflicts?
If both branches changed the same lines, the merge stops and Git marks the files:
CONFLICT (content): Merge conflict in src/index.js
Automatic merge failed; fix conflicts and then commit the result.
Open each conflicted file, decide what the final code should look like, then stage and commit:
git add src/index.js
git commit
If the conflicts are more than you want to handle right now, you can back out completely:
git merge --abort
This returns the branch to the exact state it was in before you started the merge, so there’s no risk in trying.