TechEarl

Git Branching Explained for Beginners

What a Git branch actually is, how HEAD points at your current spot, the everyday commands to create, switch, list, rename, and delete branches, plus Git tags and the team branching strategies (GitHub Flow, Git Flow, trunk-based).

Ishan KarunaratnePublished ⏱️ 17 min readUpdated
Share thisCopied
What a Git branch is, how HEAD works, the everyday branch commands (create, switch, rename, delete), Git tags, and team workflows like GitHub Flow.

A Git branch is just a movable pointer to a commit. It is not a copy of your files, not a folder, and not expensive to make. When you run git switch -c feature, Git writes a tiny file holding one commit ID and points HEAD at it. That is why you make branches constantly and throw them away freely.

This page covers what a branch and HEAD really are, the everyday branch commands (create, switch, find the current and default branch, list, rename, delete), Git tags for marking releases, and the three branching strategies teams use. If you are still getting your bearings with commits and the working tree, start with my Git for beginners series.

What a branch really is

Every commit in Git has a unique ID (a 40-character SHA-1 hash) and a pointer to its parent commit. String those parent links together and you get the history. A branch is nothing more than a named file that holds the ID of the commit at the tip of a line of work.

You can prove this to yourself. The branch is a literal file under .git/refs/heads/:

bash
cat .git/refs/heads/main
Creating and switching to a new branch, shown in git log graph output
Creating a branch, committing on it, and viewing the history graph.
text
3f8a1c9e6b2d4a7f0c1e9b8d6a3f2c1e9b8d6a3f

That is the entire branch: one line, one commit ID. When you add a new commit on main, Git updates that file to point at the new commit. The branch "moves forward" automatically. There is no copying, no cloning of files, nothing heavy happening. This is why creating a branch is instant even on a repository with years of history.

What HEAD is

HEAD is how Git tracks which branch you are currently on. It is another small file, .git/HEAD, and it almost always contains a reference to a branch rather than a raw commit ID:

bash
cat .git/HEAD
text
ref: refs/heads/main

Read that as "I am on the main branch." When you commit, Git advances whatever branch HEAD is pointing at. When you switch branches, Git rewrites HEAD to point at the new branch and updates the files in your working directory to match that branch's tip commit.

So there are two layers of indirection: HEAD points at a branch, and the branch points at a commit. That sounds like overhead, but it is exactly what lets the same commit be the tip of multiple branches, and what makes switching branches an O(1) operation.

Detached HEAD

If you ever check out a specific commit (or a tag) instead of a branch, HEAD points straight at that commit with no branch in between. Git calls this a detached HEAD, and it warns you loudly:

text
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

It is not an error. It just means new commits you make are not attached to any branch, so they are easy to lose. To keep work you did in a detached HEAD, make a branch for it: git switch -c keep-this-work. If you have already lost commits this way, they are usually recoverable; see how to recover lost commits with git reflog.

Creating and switching branches

Modern Git (2.23 and later, released August 2019) gives you two purpose-built commands: git switch for moving between branches and git restore for discarding changes. Before that, both jobs lived inside the heavily overloaded git checkout, which is still around and still works. That same overload is why checkout could also restore or throw away files, a footgun I unpack in how git switch and git checkout discard changes. I will show both here because you will see checkout everywhere in older tutorials and Stack Overflow answers.

To create a new branch and move onto it in one step:

bash
# The modern way (Git 2.23+)
git switch -c feature-login

# The classic way (works in every version of Git)
git checkout -b feature-login

Both do the same thing: create a branch named feature-login pointing at your current commit, then move HEAD onto it. The -c (switch) and -b (checkout) flags mean "create." Use -C (capital) to reset the branch if it already exists, the same way checkout -B did.

If the branch already exists and you just want to move onto it, drop the create flag:

bash
# Modern
git switch feature-login

# Classic
git checkout feature-login

To create a branch without moving onto it (you stay where you are), use git branch:

bash
git branch feature-login

Here is how the two generations of commands line up:

TaskModern command (2.23+)Classic command
Create a branch and switch to itgit switch -c namegit checkout -b name
Switch to an existing branchgit switch namegit checkout name
Create a branch without switchinggit branch namegit branch name
Go back to the previous branchgit switch -git checkout -
Create a branch from a specific commitgit switch -c name <commit>git checkout -b name <commit>

My recommendation for anyone learning today: use git switch and git restore. They were split out precisely because checkout did too many unrelated things, which made it a common source of "I ran the wrong thing and lost my changes" mistakes. Every git checkout branch command still works, so knowing it is worthwhile, but reach for switch first.

Git branch commands

These are the branch commands I actually type in a day:

bash
git branch --show-current                          # which branch am I on?
git switch other-branch                            # move to an existing branch
git switch -c new-branch                           # create and move to a new one
git switch -c hotfix main                          # create one from a named starting point
git switch -                                        # back to the previous branch
git branch -m better-name                           # rename the current branch
git branch -d feature                               # delete a merged local branch
git push origin --delete feature                    # delete the remote branch

The sections below cover listing, renaming, and deleting in detail. Three of these deserve a closer look first.

Which branch am I on?

bash
git branch --show-current

This prints just the current branch name and nothing else, which is what you want in a script or a prompt. It landed in Git 2.22 (June 2019). On an older Git, the portable fallback is:

bash
git rev-parse --abbrev-ref HEAD

One quirk: in detached HEAD state, rev-parse prints HEAD rather than a branch name, whereas git branch --show-current prints an empty line. Either is a fine signal that you are not on a branch; just know which you are testing for.

Jump back to the previous branch

git switch - means "the branch I was on before this one," exactly like cd - jumps to your previous directory. It is the fastest way to bounce between a feature branch and main without typing either name. git checkout - does the same on any Git.

Find a remote's default branch

The default branch is the one a fresh clone checks out: historically master, now usually main on new repositories. When you script against "whatever the default is," do not hardcode the name. The offline answer reads the symbolic ref your clone already stores:

bash
git symbolic-ref refs/remotes/origin/HEAD --short

That prints something like origin/main. Strip the prefix if you only want the branch name:

bash
git symbolic-ref refs/remotes/origin/HEAD --short | sed 's@^origin/@@'

That local ref is set at clone time and is not automatically updated if the remote later changes its default. If it is missing or stale, re-point it with git remote set-head origin --auto. To ask the remote directly (a network round trip, but always current), git remote show origin reports it in a HEAD branch: line:

bash
git remote show origin | sed -n '/HEAD branch/s/.*: //p'

I reach for the symbolic-ref form by default (instant and offline) and fall back to remote show origin only when I suspect the local ref is wrong.

Listing branches

To see every local branch, with the current one marked by an asterisk:

bash
git branch
text
* main
  feature-login
  bugfix-header

The branch with the * is the one HEAD is pointing at. The other listing flags:

bash
git branch -v             # each branch + its tip commit and subject
git branch -vv            # also its upstream and ahead/behind counts
git branch -a             # local + remote-tracking branches
git branch -r             # remote-tracking branches only
text
* main
  feature-login
  remotes/origin/main
  remotes/origin/feature-login

The remotes/origin/... entries (shown above by git branch -a) are Git's local record of where the branches were on the remote the last time you fetched. They are not the same as your local branches; understanding that gap is the heart of the difference between git pull and git fetch.

git branch -vv is the one I lean on most when a push is misbehaving, because it shows each branch's tracked upstream and whether you are ahead or behind. If a branch tracks the wrong upstream (or none), fix it in place without re-pushing:

bash
git branch -u origin/main              # set the current branch's upstream
git branch -u origin/main feature      # set it for a branch you are not on

-u is short for --set-upstream-to; git push -u origin feature does the same thing the first time you push a branch.

When it is time to clean up, two filters tell you which branches are safe to delete:

bash
git branch --merged       # branches already merged into HEAD: safe to delete
git branch --no-merged    # branches with commits not yet in HEAD: don't -d these

Pass a commit to either to test against something other than HEAD, for example git branch --merged main.

Renaming a branch

To rename the branch you are currently on, use -m (move) with the new name:

bash
git branch -m new-name

To rename a branch you are not on, give both names:

bash
git branch -m old-name new-name

Renaming only touches the local branch. If you have already pushed the old name to a remote, you need to push the new one and delete the old one there. This is also how people rename master to main on existing projects:

bash
git branch -m master main
git push origin main
git push origin --delete master

After that, anyone else on the repo needs to update their local copy to track the renamed branch, and you should update the default branch in your hosting provider's settings. While you are in there, it is a good moment to set up a branch protection rule on main so nobody force-pushes over the renamed branch by accident.

Deleting a branch

Once a branch is merged and you are done with it, delete it. Use -d (safe delete), which refuses to remove a branch whose commits have not been merged into its upstream or your current branch:

bash
git branch -d feature-login

If the branch has unmerged work, Git stops you:

text
error: The branch 'feature-login' is not fully merged.
If you are sure you want to delete it, run 'git branch -D feature-login'.

That is a guardrail, not a bug. If you genuinely want to throw the work away, -D (shorthand for --delete --force) forces it:

bash
git branch -D feature-login

Be deliberate with -D. It deletes the branch label, and any commits that were only reachable through that branch become "dangling." They are not instantly gone (the reflog remembers them for a while), but this is the command that strands work. You cannot delete the branch you are currently on; switch to another branch first.

Delete a remote branch

bash
git push origin --delete feature-login

Deleting the remote branch and deleting your local copy are two separate acts: this command does nothing to your local branch, and git branch -d does nothing to the remote. To fully retire a branch you run both. You will also see the older colon syntax, git push origin :feature-login, which means "push nothing into that remote ref" and deletes it; --delete says what it means, so I prefer it.

Deleting a remote branch does not clean up the stale remote-tracking ref (origin/feature-login) in other clones. Prune those with:

bash
git fetch --prune

A typical branching workflow

Here is the loop most beginners settle into, start to finish. It assumes you already have a project; if you do not, set up a fresh repository to branch from first:

bash
# Start from an up-to-date main
git switch main
git pull

# Branch off for the new work
git switch -c feature-search

# ...edit files, then stage and commit...
git add .
git commit -m "Add search box to header"

# Push the branch and set its upstream the first time
git push -u origin feature-search

The git add . step here glosses over what staging actually does; if you want a deeper look at the staging area before you commit on a branch, I cover it separately. If that commit came out wrong (bad message, a file you forgot to stage, or the wrong files entirely), it is trivial to walk it back on the branch before you push: see how to undo the last Git commit for the --soft, --mixed, and --hard reset distinctions. That -u (short for --set-upstream) links your local branch to the remote one so future git push and git pull calls need no arguments. Skip it and Git complains that the current branch has no upstream branch. For the commit step itself, a clean message helps everyone who reads the history later; I cover that in Git commit message best practices.

Once the work is done and reviewed, you merge it into main (often through a pull request) and delete the feature branch. From there, the next thing to learn is what actually happens when branches come back together: git merge versus git rebase. Once a single feature branch feels comfortable, the next step up is choosing a team branching strategy, which decides how everyone's branches fit together.

Git tags: create, push, and delete

A branch moves; a tag does not. A Git tag is a permanent, human-readable name pinned to one commit, the way you mark v1.2.0 so you can find the exact code you shipped months later. For anything you release, create an annotated tag and push it on its own:

bash
git tag -a v1.2.0 -m "Release 1.2.0"   # create an annotated tag
git push origin v1.2.0                  # push it (git push alone will NOT)

Annotated vs lightweight tags

An annotated tag is a full object in Git's database: it stores the tagger's name and email, the date, a message, and can be GPG-signed and verified. It is the right tool for a release and what release tooling and CI expect. A lightweight tag (git tag v1.2.0, no -a) is just a pointer to a commit with no metadata, fine as a private bookmark. The rule I follow: annotated for anything anyone else will see. There is a functional reason too: git describe ignores lightweight tags by default, so a release marked with one can quietly fall out of your version strings.

bash
git tag -s v1.2.0 -m "Release 1.2.0"   # GPG-signed
git tag -v v1.2.0                       # verify a signed tag
git tag -a v1.0.0 -m "Release 1.0.0" 9fceb02   # tag a past commit

By default a tag points at HEAD. To tag an older commit, pass its SHA (find it with git log --oneline), or any commit-ish such as a branch name or HEAD~3, as the last argument.

Push tags to the remote

The gotcha that catches almost everyone: git push does not push tags. Push them explicitly:

bash
git push origin v1.2.0        # one tag (deliberate, my preference)
git push origin --tags        # every tag the remote does not have
git push --follow-tags        # the branch plus annotated tags on the pushed commits

--follow-tags ignores lightweight tags, which is another reason to annotate releases. Make it the default with git config --global push.followTags true.

List, inspect, and delete tags

bash
git tag                       # list all tags
git tag -l "v1.*"             # filter with a glob
git show v1.2.0               # what the tag points at, plus its message

For an annotated tag, git show prints the tag object header and then the commit; for a lightweight tag you just get the commit, which is a quick way to tell them apart.

A pushed tag lives in two places, and deleting it locally does not touch the remote:

bash
git tag -d v1.2.0                   # delete the local tag
git push origin --delete v1.2.0     # delete it on the remote

The old syntax git push origin :refs/tags/v1.2.0 does the same thing. Checking out a tag (git checkout v1.2.0) puts you in detached HEAD; to make changes from that point, branch off it first:

bash
git switch -c hotfix-1.2.1 v1.2.0

Git branching strategies for teams

A branching strategy is the agreement a team makes about how branches are created, reviewed, and merged. Every strategy answers the same questions: where new work starts, how long a branch lives, what must happen before code lands (review, CI, both), and whether main is always deployable. Three come up by name.

GitHub Flow: one main branch, short feature branches

There is exactly one long-lived branch, main, and it is always deployable. Everything else is a short-lived branch off main that lives only long enough to finish one piece of work: the typical workflow above, followed by a pull request, review, CI, merge, and deleting the branch. Deploy happens from main.

It optimizes for speed and simplicity, and fits web apps and services where "the latest main" and "what is in production" are meant to be the same thing. The trade-off: you need a way to keep half-finished work from breaking main, which usually means feature flags for anything large, a protected main branch that blocks direct pushes, and a continuous integration pipeline so nothing merges without the tests running.

Git Flow: develop, release, and hotfix branches

Git Flow, the model Vincent Driessen described in 2010, defines several long-lived and supporting branches:

  • main holds only released, tagged versions. Every commit on it is a production release.
  • develop is the integration branch where finished features accumulate between releases.
  • feature/* branches come off develop and merge back into it.
  • release/* branches fork from develop to stabilize a version, then merge into both main and develop.
  • hotfix/* branches come off main to patch production, then merge back into both.

It optimizes for managing multiple versions in flight: installable software, several supported releases, a formal QA-then-release cadence. For a team that just deploys a web app continuously, it is ceremony with no payoff, and it makes merge conflicts more frequent because branches live longer and drift further apart. Even the original author later noted it was designed for versioned-release software, not continuously delivered web apps.

Trunk-based development: tiny branches, merged daily

There is one trunk (main), and branches are tiny and short-lived: hours, not days, merged back the same day. Many teams running this push to main several times per developer per day. Because changes are so small, integration pain mostly disappears, and unfinished features hide behind feature flags rather than long-lived branches. It is the workflow most associated with high-performing teams in the DevOps research, but it demands strong automated tests and a real CI pipeline: with weak tests, "commit to main many times a day" just means breaking main many times a day.

GitHub FlowGit FlowTrunk-Based
Long-lived branchesmain onlymain + developmain (trunk) only
Branch lifetimeHours to daysDays to weeksHours
Optimizes forSimplicity, fast deliveryVersioned releases, multiple versions in flightContinuous integration, high deploy frequency
Code reviewPull request per branchPull request into developPR or pair, kept very small
Release modelDeploy from mainStabilize on release, tag on mainDeploy from trunk, flags hide WIP
CI requirementRecommendedRecommendedMandatory, strong tests
Best forMost small web/service teamsInstallable/versioned softwareMature teams with solid automation

How to pick one for a small team

Default to GitHub Flow. For a team of two to ten people shipping a web app or a service, it gives you review and a deployable main without the branch bookkeeping. Reach for Git Flow only if "version 2.3 is in production, 2.4 is in QA, and someone needs a hotfix on 2.3" is a real sentence in your week. Move toward trunk-based development as the team matures and the test suite gets strong enough to trust; it is less a starting point than a destination.

Whatever you pick, write it down and protect main: a branch protection rule is what turns a written convention into an enforced one. The strategy decides when branches merge, not how; keeping merge commits or rebasing for a linear history is a separate choice covered in git merge vs git rebase. A common pairing is GitHub Flow plus a squash-merge on the PR, so each feature lands as one tidy commit; squashing with interactive rebase cleans up a branch before review.

git switch only changes branches, while git checkout does that plus several unrelated jobs like restoring files and detaching HEAD. Git split switch and restore out of checkout in version 2.23 to make each command do one clear thing. For changing branches, prefer git switch. The older git checkout still works everywhere, which is why you see it in most older tutorials.

No. A branch is just a small file holding one commit ID, so creating one is instant and costs almost no disk space no matter how large the repository is. Git does not duplicate your project. It only updates which commit your working directory reflects when you actually switch onto a branch.

HEAD is a pointer to the branch you are currently on, which in turn points at a commit. When you commit, Git advances whatever branch HEAD references. When you check out a specific commit instead of a branch, HEAD points straight at that commit, which is called a detached HEAD.

Run git branch --show-current (Git 2.22 and newer). It prints only the branch name, which is what you want in a script or shell prompt. On older Git, use git rev-parse --abbrev-ref HEAD, noting that it prints HEAD in detached-HEAD state rather than an empty line.

You cannot. Git refuses to delete the branch that HEAD is pointing at because it would leave you with no current branch. Switch to another branch first, for example git switch main, and then delete the one you no longer need with git branch -d.

Because git push does not push tags. Push the tag explicitly with git push origin v1.2.0, or all of them with git push origin --tags. To push annotated tags along with a branch automatically, use git push --follow-tags.

GitHub Flow for most small teams: one always-deployable main branch, short-lived feature branches, and code review through pull requests. Reach for Git Flow only if you ship versioned software, and move toward trunk-based development as your automated tests get strong enough to trust merging into main every day.

It is strongly recommended for GitHub Flow and Git Flow, and mandatory for trunk-based development. Merging frequently into a shared branch only works if automated tests catch breakage before it spreads.

Sources

Authoritative references this article was fact-checked against.

TagsGit BranchingGitVersion Controlgit switchgit checkoutgit branchgit tagGitHub FlowGit Flow

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

How JavaScript promises work: states, async/await, Promise.all vs allSettled vs race vs any, concurrency limits, polling, debounce and throttle, and mistakes.

JavaScript Promises Explained: A Complete Guide

How JavaScript promises actually work: the three states, .then/.catch/.finally, async/await, Promise.all vs allSettled vs race vs any, limiting concurrency with a promise pool, sleep and polling, debounce and throttle, what async functions desugar to, and the promise mistakes that bite in production.

Bash for and while loop examples: arrays, files with spaces, ranges, reading a file line by line, retry with backoff, and the while read subshell bug.

Bash For Loops: Syntax, Examples, and One-Liners

Every form of the Bash for loop with working examples: brace-range, sequence-expression, array, glob, C-style, nested, and parallel. Plus the while loop (read a file line by line, retry with backoff, wait for a service), until and select, the safe file-iteration patterns, common pitfalls, and macOS Bash 3.2 vs Linux Bash 4+ gotchas.