Tutorial 3 · beginner · 12 min

Branching and merging

Create branches, switch between them, and merge them back. This is the building block of every Git workflow.

Updated

A branch is just a movable pointer to a commit. Creating one is instant and costs almost nothing. That’s why every Git workflow, including Gitflow, is built on branches.

Create and switch

git switch -c feature/greeting   # create + switch (older Git: git checkout -b)
git branch                        # list branches; * marks the current one

Make a commit on the new branch:

echo "Hello!" > greeting.txt
git add greeting.txt
git commit -m "Add greeting"

Switch back. greeting.txt disappears because main doesn’t have it yet:

git switch main

Merge

git merge feature/greeting

If main hasn’t moved since you branched, Git does a fast-forward: it simply slides the main pointer forward. No merge commit is created.

To always record a merge commit (Gitflow does this, so a feature’s history stays grouped):

git merge --no-ff feature/greeting

Merge conflicts

If both branches changed the same lines, Git stops and marks the file:

<<<<<<< HEAD
Hello from main
=======
Hello from the feature
>>>>>>> feature/greeting

To resolve it:

  1. Edit the file to the version you want and delete the markers.
  2. git add <file>
  3. git commit (or git merge --continue)

Changed your mind? git merge --abort puts everything back as it was.

Clean up

git branch -d feature/greeting    # deletes only if merged

Next

You now know everything Gitflow is built from. See the Gitflow workflow, step by step.

One Git tip a week

Short, practical, no spam. Get the free printable Gitflow cheat sheet when you join.

Newsletter launching soon.