Merging is one way to keep one branch synchronized with another.
When working in parallel branches, you’ll often need to sync (short for synchronize) one branch with another. For example, while developing a feature in one branch, you might want to bring in a recent bug fix from another branch that your branch doesn’t yet have.
The simplest way to sync branches is to merge — that is, to sync a branch b1 with changes from another branch b2, you merge b2 into b1. In fact, you can merge them periodically to keep one branch up to date with the other.
gitGraph
%%{init: { 'theme': 'default', 'gitGraph': {'mainBranchName': 'main'}} }%%
commit id: "m1"
branch bug-fix
branch feature
commit id: "f1"
checkout main
checkout bug-fix
commit id: "b1"
checkout main
merge bug-fix
checkout feature
merge main id: "mc1"
commit id: "f2"
checkout main
commit id: "m2"
checkout feature
merge main id: "mc2"
checkout main
commit id: "m3"
checkout feature
commit id: "[feature] f3"
checkout main
commit id: "[HEAD → main] m4"
In the example above, you can see how the feature branch is merging the main branch periodically to keep itself in sync with the changes being introduced to the main branch.
Preparation Run the following commands to create a sample repo that we'll use for this hands-on practical:
mkdir samplerepo-sync
cd samplerepo-sync
git init -b main
echo "v1" > app.txt
git add .
git commit -m "m1: initial commit"
git branch bug-fix
git switch -c feature
echo "new feature" >> feature.txt
git add .
git commit -m "f1: start feature"
git switch bug-fix
echo "fix" >> app.txt
git commit -am "b1: fix a bug"
Target Bring the fix from bug-fix into main, then sync feature with main, so that feature also gets the fix.
1 Merge bug-fix into main.
git switch main
git merge bug-fix
Switch to the main branch, then right-click on the bug-fix branch and choose merge bug-fix into the current branch.
Because main had not diverged from bug-fix, Git fast-forwards main -- no merge commit is created.
2 Sync feature with main by merging main into feature.
git switch feature
git merge main
Switch to the feature branch, then right-click on the main branch and choose merge main into the current branch.
This time, feature and main have diverged (each has a commit the other lacks), so Git creates a merge commit. Run git log --oneline --graph --all to see that feature now contains the fix from b1, alongside its own commit f1.
You could repeat this merge periodically -- for example, each time main gets a new commit -- to keep feature up to date, as illustrated in the revision graph earlier in this lesson.
done!