Chapter 6 · Lesson 5 of 10
Git for deployers

Git branches and merging: create, switch, merge, delete

A Git branch is a movable label on a commit, so you can build a change on its own line of history and then combine it into main with git merge.

By the end you will

Create a branch, commit on it, merge it into main, delete it, and read the branch history with git log --graph.

Time
15 min
Level
Beginner
Check
4 questions
You need
  • A repository with at least one commit

A branch lets you work apart, then merge back

A branch is a movable pointer to a commit, so you can build a feature apart from main and merge it back when it is ready.
  1. git switch -c feature starts a new branch that points at the same commit as main.
  2. Commits you make now move only the feature branch, building up the work to merge.
  3. Other work can land on main meanwhile, and the merge will combine it with your branch.
  4. Merging combines the feature commits with main into a merge commit.
  5. main now points at the merge result and holds the finished feature.
Static diagram
  1. mainbranch offFeature branch
  2. Feature branchcommitMerge commit
  3. mainmain movesMerge commit
  4. Feature branchgit mergeMerge commit
  5. Merge commitmain updatedmain

A Git branch is a movable label on a commit. You create one with git switch -c name, commit on it without touching main, then bring the work back with git merge. Branches cost almost nothing, so the usual habit is one branch per change and a merge when it is done.

How it works#

Every commit points to its parent. A branch is just a name that points to one commit, and Git moves that name forward each time you commit while on it. HEAD says which branch you are on. Because a branch holds no copy of your files, creating one is instant and takes almost no space.

When two lines of history need to come together, Git merges them. There are two outcomes:

  • Fast-forward. main has not changed since you branched, so Git slides the main label forward to your latest commit. No new commit is created, and history stays a straight line.
  • Merge commit. Both main and your branch gained commits. Git builds a new commit with two parents that combines both. If the same lines changed on both sides you get a merge conflict.

Before starting, you need a repository with a commit, as made in your first repository.

Step 1: Create and switch to a branch#

bash
git branch                   # list branches, * marks the current one
git switch -c feature-health # create and switch

git switch -c is the short form of creating a branch and moving onto it. Older guides use git checkout -b, which still works. Pick short, descriptive names, such as fix-login-redirect or feature-health. Slashes are allowed (feature/health).

Step 2: Commit on the branch#

Edit files and commit as usual:

bash
echo "ok" > health.txt
git add health.txt
git commit -m "add health page"

main does not see this commit. Run git switch main and health.txt disappears from your folder, then git switch feature-health and it returns. Git rewrites the working tree for you. If you have uncommitted edits that would be overwritten, Git refuses to switch and tells you, so commit or stash first.

Step 3: Merge the branch#

Go to the branch that should receive the work, then merge:

bash
git switch main
git merge feature-health

Output beginning with Updating ... and Fast-forward means main simply moved. If main had new commits, Git opens your editor for a merge commit message (the default is fine) and prints Merge made by the 'ort' strategy.

Two options to know:

bash
git merge --no-ff feature-health   # always create a merge commit
git merge --ff-only feature-health # fail unless a fast-forward is possible

--no-ff keeps the branch visible in history. --ff-only is useful on servers so a pull never creates an unexpected merge.

Step 4: Delete the branch#

bash
git branch -d feature-health

-d deletes only if the branch is merged. -D forces deletion, and the commits not in any other branch become unreachable, though the reflog can still find them for a while. Deleting a branch does not undo the merge: the commits stay in main.

Step 5: Read the shape with git log —graph#

bash
git log --oneline --graph --decorate --all

--graph draws the branches with * and lines, --decorate shows branch and tag names, and --all includes branches other than the current one. A merge commit shows as a * with two lines joining it. This command is worth an alias:

bash
git config --global alias.lg "log --oneline --graph --decorate --all"

Branch-per-change is also the base of every CI/CD pipeline, and tidy history makes a rollback easier. For a whole deploy built on branches, read the blog post Deploy an Express app with Docker on a VPS, and see undo mistakes if a merge goes wrong.

Check it worked#

After the merge, git log --oneline on main shows your branch’s commit, and git branch no longer lists the deleted branch. git status should say nothing to commit, working tree clean. If you used --no-ff, git log --graph shows the merge commit.

Edge cases and gotchas#

  • Merge direction matters. You merge into the branch you are on. Check with git branch before running git merge.
  • Uncommitted changes travel with you. If they do not conflict, Git carries them to the other branch. That surprises people, so run git status before switching.
  • Squash merges lose the branch history. git merge --squash stages all the changes as one commit, and the branch commits are not recorded as parents. Many pull request hosts offer this as a button.
  • Merged does not mean pushed. A local merge changes your main only. Share it with push.
  • Long-lived branches drift. The longer a branch lives, the larger the conflicts at merge time. Merge main into it regularly, or keep branches short.
  • Branch names are case sensitive on Linux. Feature and feature are different branches, which causes trouble on macOS and Windows checkouts.

Troubleshooting#

SymptomLikely causeFix
fatal: a branch named 'feature-health' already existsThe name is takenPick another name, or git switch feature-health
error: pathspec 'feature-health' did not match any file(s) known to gitTypo, or the branch is not fetched yetCheck git branch -a, and git fetch for remote branches
error: Your local changes to the following files would be overwritten by checkoutUncommitted edits clash with the other branchCommit or git stash push, then switch
error: The branch 'feature-health' is not fully merged.-d found unmerged commitsMerge first, or git branch -D if you want to discard them
Automatic merge failed; fix conflicts and then commit the result.Both sides edited the same linesResolve the conflict, see the next lesson
fatal: Not possible to fast-forward, aborting.--ff-only used and main has divergedMerge without --ff-only, or rebase the branch
fatal: refusing to merge unrelated historiesThe two branches share no common commitCheck you are in the right repository, or add --allow-unrelated-histories deliberately
Already up to date.The branch has nothing new for the targetYou may have merged the wrong way round

Quick reference#

bash
git branch                          # list local branches
git switch -c name                  # create and switch
git switch name                     # switch
git merge name                      # merge name into current branch
git merge --no-ff name              # force a merge commit
git branch -d name                  # delete merged branch
git branch -D name                  # force delete (may lose commits)
git log --oneline --graph --all     # draw the history

Next#

When a merge stops with conflicts, go to resolve Git merge conflicts.

Try it: Branch, commit and merge

Create a feature branch, commit on it, merge it into main and delete it. Hashes in the output differ on your machine.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which command creates a branch called feature-login and switches to it?
2When does Git do a fast-forward merge?
3Which merge option always creates a merge commit, even if a fast-forward is possible?
4What does git branch -d do when the branch is not merged?

Frequently asked questions

What is a branch in Git?

A branch is a lightweight pointer to a commit. When you commit while on a branch, the pointer moves forward to the new commit. Creating a branch copies nothing, so it is instant.

What is the difference between git switch and git checkout?

git switch only changes branches, and git switch -c creates one. git checkout does that and also restores files, which is why newer Git added switch and restore as clearer commands.

What is a fast-forward merge?

A fast-forward happens when main has not moved since you branched. Git just moves the main label forward to your last commit, with no merge commit.

How do I delete a branch in Git?

Run git branch -d name to delete a branch that is already merged, or git branch -D name to force-delete an unmerged one. Deleting removes the label, not the commits that were merged.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios