DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

Git & GitHubLesson 3 of 13
Your progress · 0%
On this page
  1. A branch is a pointer
  2. Create, list and rename
  3. Switching branches
  4. Merging a finished branch
  5. Deleting branches
  6. Choose a branching strategy deliberately
↖ Course roadmap
Lesson 3 · Branching

Branches: work on many things without breaking main

What a branch really is (a movable pointer to a commit), how to create, rename, switch and delete branches, carry uncommitted work safely, and merge a finished branch back into main.

30 min read · beginner · hands-on

By the end of this lesson you'll be able to

0 of 6 complete

A branch is a pointer

Why branches exist. Imagine you're halfway through a new coupon feature: three files changed, tests failing, nothing ready to ship. Then production breaks and you need a one-line fix out in ten minutes. Without branches, your half-finished coupon work is mixed into the same files. You either ship it broken along with the fix, or copy the project to another folder and fix it there, then copy the fix back and hope you didn't miss anything.

With branches, each line of work lives separately. The coupon work stays on feature/coupons. You switch to main, make the fix on a new fix/checkout-crash branch, merge and deploy it, then switch back to your coupons exactly where you left them. Nothing leaks between the two.

How it works. Most people imagine a branch as a copy of the code. It isn't. A branch is a tiny file holding one commit ID. Commits point back to their parents, and a branch just marks the newest one in a line of work:

Branches point at commits. HEAD points at your branch. Committing moves only the branch you're on.© Diagram: DevOps Academy

Branches point at commits. HEAD points at your branch. Committing moves only the branch you're on.© Diagram: DevOps Academy
$ cat .git/HEAD                   # where you are: a branch
ref: refs/heads/main
$ cat .git/refs/heads/main        # what main is: one commit ID
9c53c908c97e192de201aed90f9063ca0ba0ade9
cat .git/HEAD
  • catprint a file

That's the whole trick. Creating a branch writes 41 bytes, so it's instant even in a huge repository. Make them freely: one per feature, fix or experiment.

Create, list and rename

A branch always starts from a commit: by default the one you're on now. git switch -c creates the branch and moves you onto it in one step, which is what you want 90% of the time. Plain git branch <name> creates it without moving you, for when you want to mark a starting point and carry on where you are.

$ git switch -c feature/coupons   # create a branch here, and switch to it
Switched to a new branch 'feature/coupons'
$ git branch                      # * marks the current branch
* feature/coupons
  main
$ git branch -m feature/coupon-codes   # rename the current branch
$ git branch -v                   # with each branch's last commit
* feature/coupon-codes 0438c28 Add an empty coupon table
  main                 dad9c23 Add the app entry point
$ git branch hotfix main          # create from another starting point, without switching
git switch -c feature/coupons
  • gitversion control

Naming branches

Use a short type, a slash and a description in lowercase with hyphens. Teams and CI tools rely on these prefixes (a pipeline may deploy every release/* branch, for example):

PrefixForExample
feature/new functionalityfeature/coupon-codes
fix/bug fixesfix/empty-cart-crash
chore/tooling, dependencieschore/upgrade-node-22
docs/documentationdocs/setup-guide
release/, hotfix/release processeshotfix/1.4.1

Add the issue number when you have one: fix/142-empty-cart.

Git Tutorial #5: How to Create a Git Branch | Learn Git with GitKrakenGitKraken · Watch on YouTube ↗

Switching branches

$ git switch main                 # go to an existing branch
$ git switch -                    # back to the previous branch
$ git checkout main               # the older command; does the same here
git switch main
  • gitversion control
git switch -
  • -the previous directory

Switching changes the files in your working folder to match that branch. coupons.py exists on feature/coupon-codes and disappears when you switch to main; it comes back when you switch again. Nothing is lost: it's in the commit.

Uncommitted changes travel with you when they don't conflict with the other branch. If they would be overwritten, Git refuses to switch:

error: Your local changes to the following files would be overwritten by checkout:
	app.py
Please commit your changes or stash them before you switch branches.

Commit them, or put them aside with git stash (the Undoing changes lesson). git switch is the modern command for branches only. git checkout also restores files, which is why newer Git split it into switch and restore.

Merging a finished branch

Watch the labels: each commit moves only the branch you're on. The merge commit M joins both lines into main.© Animation: DevOps Academy

Watch the labels: each commit moves only the branch you're on. The merge commit M joins both lines into main.© Animation: DevOps Academy

When work on a branch is done, you merge it into main. There are two outcomes:

$ git switch main
$ git merge feature/coupon-codes
Updating dad9c23..0438c28
Fast-forward
 coupons.py | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 coupons.py
git switch main
  • gitversion control

Fast-forward: main had no new commits since the branch started, so Git just moved main forward to the branch's commit. No new commit is needed.

When both branches have new commits, Git combines them in a merge commit, which has two parents:

$ git merge fix/readme
Merge made by the 'ort' strategy.
 README.md | 1 +
 1 file changed, 1 insertion(+)
$ git log --oneline --graph
*   9c53c90 Merge branch 'fix/readme'
|\
| * 26df073 Document how to run the app
* | 032e8d2 Add VERSION file
|/
* 0438c28 Add an empty coupon table
* dad9c23 Add the app entry point
git merge fix/readme
  • gitversion control
git log --oneline --graph
  • loghistory

If both branches changed the same lines, Git stops and asks you to resolve a conflict. The Merge strategies lesson covers conflicts, rebasing and squashing in detail.

Deleting branches

A merged branch has done its job. Delete it so git branch stays readable:

$ git branch -d feature/coupon-codes   # safe: only if merged
Deleted branch feature/coupon-codes (was 0438c28).
$ git branch -d spike
error: the branch 'spike' is not fully merged
$ git branch -D spike                  # force: you're sure the work isn't needed
Deleted branch spike (was 1bae2b4).
$ git branch --merged main             # branches already merged into main: safe to delete
git branch -d feature/coupon-codes
  • gitversion control

Deleting a branch deletes the pointer, not the commits. For a while afterwards the commits can still be recovered with git reflog, using the ID Git printed ("was 1bae2b4").

-d (lowercase) is the safe one: Git refuses if the branch has commits that aren't merged anywhere, because deleting it would make that work hard to find. -D (uppercase) deletes anyway; use it only for experiments you're sure you don't need.

Your local copy and the copy on GitHub are separate. After a pull request is merged, GitHub can delete the remote branch for you; otherwise delete it with git push origin --delete feature/coupon-codes.

In a team

main should always be deployable. Nobody commits to it directly: work happens on short-lived branches that are merged through pull requests (the Collaboration lesson). Branches that live for weeks drift from main and end in painful merges, so merge small pieces often.

Choose a branching strategy deliberately

Every team needs a shared rule for how branches are used. There are three common ones, from simplest to heaviest:

  • Trunk-based development. Everyone branches off main (the "trunk"), keeps the branch for a day or two, and merges back through a pull request. Branches stay small, so merges stay easy, and main is always close to what's in production. It's the best fit when you deploy often, and the default most teams should start with.
  • Release branches. Same as trunk-based, but when a version is ready you cut release/2.4 from main and only bug fixes go into it, while new work continues on main. Useful when customers run several versions at once (mobile apps, installed software). The cost: every fix must be copied to both main and the release branch (with cherry-pick, in the Merge strategies lesson).
  • GitFlow. Adds a long-lived develop branch next to main, plus feature, release and hotfix branches. It was popular for software released every few months. For a web app deployed every day it's mostly overhead: more branches to keep in sync and more merges to resolve.

When unsure, choose trunk-based and add release branches only when you actually support more than one version.

Trunk-based: small branches, frequent merges. Release branches: longer-lived fixes and more coordination.© Diagram: DevOps Academy

Trunk-based: small branches, frequent merges. Release branches: longer-lived fixes and more coordination.© Diagram: DevOps Academy
$ git log --oneline --graph --decorate --all
$ git branch --merged main
$ git switch -c feature/short-lived-change
git log --oneline --graph --decorate --all
  • gitversion control
  • loghistory
⌘
Mini mission

Ship a feature and a fix in parallel

While building a coupon feature on its own branch, a README fix is needed urgently. Do the fix on a second branch, merge it first, then finish and merge the feature. End with a clean main, both branches deleted, and a history graph that shows what happened.

Input: The shop repository from the Commits lesson (or any repository)Output: main with both changes; git log --graph showing the merge
Reveal one safe solution
$ git switch -c feature/coupons
$ echo 'COUPONS = {"WELCOME10": 10}' > coupons.py
$ git add coupons.py && git commit -m "Add the coupon table"
$ git switch main && git switch -c fix/readme        # urgent fix, from main
$ echo "Run: python app.py" >> README.md
$ git commit -am "Document how to run the app"
$ git switch main && git merge fix/readme            # fast-forward
$ git switch feature/coupons
$ echo 'def discount(code): return COUPONS.get(code, 0)' >> coupons.py
$ git commit -am "Look up coupon discounts"
$ git switch main && git merge --no-edit feature/coupons   # merge commit
$ git branch -d fix/readme feature/coupons
$ git log --oneline --graph
*   70b46cf Merge branch 'feature/coupons'
|\
| * ebe3728 Look up coupon discounts
| * 63892d4 Add the coupon table
* | f0952f8 Document how to run the app
|/
* dad9c23 Add the app entry point
git switch -c feature/coupons
  • gitversion control
echo 'COUPONS = {"WELCOME10": 10}' > coupons.py
  • echoprint text
  • >write output to a file, replacing it
git add coupons.py && git commit -m "Add the coupon table"
  • addstage changes
  • &&run the next command only if this one worked
  • commitsave staged changes
echo "Run: python app.py" >> README.md
  • >>append output to a file
git log --oneline --graph
  • loghistory

git commit -am stages every tracked file that changed and commits it; it never adds new files. The fix merged as a fast-forward because main hadn't moved; the feature needed a merge commit because main had the fix by then.

Try it yourself

0 of 6 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 5

What is a Git branch, technically?

Go deeper

Official reading for this lesson

  • GuidePro Git: branches in a nutshellPro Git ↗
  • GuidePro Git: basic branching and mergingPro Git ↗
  • Docsgit-switch documentationGit ↗
  • ToolLearn Git Branching (interactive)Learn Git Branching ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousCommits: the working folder, the staging area and historyNext lesson →GitHub: your account, repositories, forks and clones