1. Home
  2. Blog
  3. DevOps

DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

git branch manages the lines of development in a repository: listing, creating, renaming and deleting branches, checking what is merged, and tracking remotes. Learn every everyday form, why Git refuses to delete some branches, how to recover a branch you deleted by mistake, and naming habits that keep teams sane, all run in a real repository.

9 min read
Git branch explained: create, switch, rename, delete and recover

Key takeaways

  • A branch is just a movable pointer to a commit; creating one is instant and costs almost nothing.
  • git branch name creates a branch but does not switch to it; git switch -c does both.
  • git branch -d refuses to delete unmerged work; -D forces it, and the reflog can still bring it back.
  • git branch --merged and --no-merged show what is safe to clean up.

Branches are how Git lets you work on a feature, a fix and an experiment at the same time without them interfering. The git branch command is the control panel for those lines of work. Most developers use only two or three of its forms, and then panic the first time Git refuses a delete or a branch seems to vanish. This guide covers the whole everyday toolkit.

We ran every command with Git 2.56 in a throwaway repository, using a placeholder identity (Demo, demo@example.com) and fixed dates, and show the real output. New to Git? Read our Git commands cheat sheet first.

What is a Git branch?

A branch is a named pointer to a commit, stored as a tiny file in .git/refs/heads/. When you commit on a branch, the pointer moves forward to the new commit. HEAD is another pointer that says which branch you are currently on. That is why branches in Git are so cheap: creating one writes about 41 bytes, it does not copy any files.

Listing branches

git branch
* main

Plain git branch lists local branches and marks the current one with an asterisk. git branch --show-current prints just the current name, handy in scripts and shell prompts.

Creating a branch

git branch feature/login
git branch
  feature/login
* main

The new branch points at the current commit, but you are still on main. This surprises beginners who then commit to the wrong branch. Creating without switching is useful when you want to bookmark the current commit or prepare several branches at once.

Create and switch in one step

git switch -c feature/search
Switched to a new branch 'feature/search'
git branch --show-current
feature/search

git switch -c (or the older git checkout -b) creates the branch and moves to it. git switch was introduced to separate “change branch” from the many other jobs of checkout; use git switch name to move to an existing branch and git switch - to jump back to the previous one.

Seeing where each branch points

git branch -v
  feature/login  328e91d Add cart
  feature/search 0abfe1d Add search
* main           328e91d Add cart

-v shows each branch’s latest commit. Here feature/login and main point to the same commit, while feature/search has one extra commit, “Add search”. For a full picture of how branches diverge, use the graph view from our git log guide.

Branching from an older commit

git branch hotfix HEAD~1
git log --oneline -1 hotfix
ee55da0 Initial commit

Give a commit, tag or branch name as the second argument to start the branch somewhere else. Starting a hotfix from the last release tag, for example git branch hotfix/1.2.1 v1.2.0, is a common pattern; see git tag.

Which branches are merged?

git branch --merged
  feature/login
  hotfix
* main
git branch --no-merged
  feature/search

--merged lists branches whose commits are all reachable from the current branch, so deleting them loses nothing. --no-merged lists branches with unique work. Run both from main before a cleanup.

Deleting branches

git branch -d feature/search
error: the branch 'feature/search' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D feature/search'

git branch -d feature/login
Deleted branch feature/login (was 328e91d).

-d is the safe delete: it refuses when the branch has commits that are not merged, protecting unfinished work. feature/login had nothing unique, so it was deleted. Note the (was 328e91d): Git prints the commit the branch pointed to, which is your lifeline if you change your mind.

git switch hotfix/cart-total
git branch -d hotfix/cart-total
error: cannot delete branch 'hotfix/cart-total' used by worktree at '.../gb'

You also cannot delete the branch you are standing on; switch away first. (We shortened the folder path in the message.) To delete despite unmerged work, use the capital -D:

git branch -D feature/search
Deleted branch feature/search (was 0abfe1d).

Renaming a branch

git branch -m hotfix hotfix/cart-total
git branch
  feature/search
  hotfix/cart-total
* main

git branch -m old new renames any local branch; git branch -m new renames the current one. This is how many teams renamed master to main. Renaming is local only: for a pushed branch, push the new name, set the upstream, and delete the old remote branch with git push origin --delete old. Warn teammates first, because their local copies still track the old name.

Recovering a deleted branch

git reflog | grep "Add search" | head -1 | cut -d' ' -f1
0abfe1d
git branch feature/search 0abfe1d
git log --oneline -1 feature/search
0abfe1d Add search

Deleting a branch removes only the pointer; the commits stay in the repository until garbage collection, usually weeks later. Use the hash from the delete message, or find it in git reflog, and create a branch at that commit. We force-deleted feature/search and brought it back in one command.

Tip: copy the “was abc1234” hash when you delete a branch. It turns any accidental delete into a one-line fix.

Filtering and sorting branches

git branch --list "feature/*"
  feature/search

git branch --sort=-committerdate --format="%(refname:short) %(committerdate:short)"
feature/search 2026-11-22
hotfix/cart-total 2026-11-22
main 2026-11-22

git branch --contains HEAD~1

In repositories with hundreds of branches, filter with --list patterns, sort by recent activity, and ask which branches contain a given commit, useful for “has this fix reached the release branch?”. --format accepts the same placeholders as git for-each-ref.

Remote branches and tracking

git push -u origin main
git branch -vv
* main  328e91d [origin/main] Add cart
git branch -r
  origin/main
git branch -a
  feature/search
  hotfix/cart-total
* main
  remotes/origin/main

We pushed to a local bare repository standing in for a server. -u set origin/main as the upstream, which -vv shows in brackets. -r lists remote-tracking branches and -a lists everything. Remote-tracking branches are read-only snapshots updated by git fetch; run git fetch --prune to drop ones deleted on the server. Merge strategies between branches are covered in our merge vs rebase guide.

Branch naming conventions

  • Use prefixes: feature/, fix/, hotfix/, release/, chore/.
  • Include the ticket ID: feature/SHOP-142-coupon-codes.
  • Lowercase words separated by hyphens; no spaces.
  • Keep branches short-lived and delete them after merging.
  • Protect main on the server so changes arrive through reviewed pull requests.

Git branch cheat sheet: 12 commands

Task Command
List local branches git branch
Show current branch git branch --show-current
Create a branch git branch name
Create and switch git switch -c name
Branch from a commit or tag git branch name v1.2.0
Latest commit per branch git branch -v
Safe to delete git branch --merged
Delete merged branch git branch -d name
Force delete git branch -D name
Rename git branch -m old new
Remote and tracking info git branch -vv
Restore a deleted branch git branch name <hash>

To set work aside without a branch, see git stash.

Branching strategies at a glance

Strategy How it works Suits
Trunk-based development Short-lived branches merged into main at least daily, with feature flags for unfinished work Teams with strong CI and frequent releases
GitHub flow Branch from main, open a pull request, merge after review, deploy main Web apps and services with continuous delivery
Git flow Long-lived develop and main branches plus feature, release and hotfix branches Versioned products with planned release cycles

The commands are the same in every strategy; what changes is how long branches live and where they merge. Shorter-lived branches mean smaller merges and fewer conflicts, which is why many teams have moved towards trunk-based development combined with feature flags.

Final thoughts

git branch is simple once you see branches as pointers. Create them freely, switch with git switch, check --merged before cleaning up, use -d for safe deletes and -D only when you mean it, and remember that the reflog can restore almost any branch. With consistent names and short-lived branches, your repository stays easy to navigate for the whole team.

Frequently asked questions

How do I create a new branch in Git?

Run git branch followed by the name to create it, or git switch with the c option and the name to create it and switch to it in one step.

How do I delete a Git branch?

Use git branch with the d option for a branch that is fully merged. Git refuses if there is unmerged work; use the capital D option to force the delete.

How do I rename a Git branch?

Use git branch with the m option followed by the old and new names, or just the new name for the current branch. For pushed branches, also push the new name and delete the old remote branch.

Can I recover a deleted Git branch?

Yes. Find the commit hash in the delete message or in git reflog, then run git branch with the branch name and that hash to recreate it.

How do I see which branches are merged?

Run git branch with the merged option to list branches fully merged into the current branch, and with the no-merged option to list branches that still contain unique commits.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →