Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 78 ยท Branching and Merging

Branch Management and Cleanup

Manage Git branches over time: list merged and unmerged branches, delete them safely, set up tracking branches, prune stale remote branches and keep a tidy repository.

Creating branches is easy. Living with them is the harder part. After a few months a busy repository has dozens of branches: some merged long ago, some abandoned, some still active, and some that only exist on a server. Without a little housekeeping you lose track of what is finished, git branch becomes a wall of names, and people start asking "is it safe to delete fix-login-2?"

This lesson gives you the tools to answer that question with certainty: how to list branches that are merged or not merged, delete them safely in one go, understand tracking branches that link your local branch to a remote one, remove stale references with pruning, and decide how long branches should live. It builds on Branches and Merging.

What "merged" means

A branch is merged into another when its tip commit is reachable from the other branch: every commit on it is already part of the other branch's history. At that point the branch name is redundant. Deleting it removes only the pointer; the commits stay in main.

Two flags answer the question directly, always relative to a commit (the current branch by default):

  • git branch --merged lists branches already contained in the current branch.
  • git branch --no-merged lists branches that still hold commits the current branch lacks.

Add a branch name (git branch --merged main) to ask about a branch other than the current one. This is usually what you want, so you do not depend on where you happen to be standing.

Bash Which branches are merged into main?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

done-feature is merged because the merge commit includes its tip. old-spot counts as merged too, which can look odd: it points at a commit that main has long contained, so there is nothing to lose by deleting it. wip-feature is the only one that holds unique work. The current branch (main) always lists itself as merged.

Squash and rebase merges fool this check. If your team merges pull requests by squashing, the branch's commits are not in main's history (a new, different commit was made), so --merged reports the branch as unmerged even though its content landed. Judge those branches by the pull-request status on your platform, or compare content with git diff main...branch. See Pull Requests and Code Review.

Deleting safely, one branch or many

As Branches showed, git branch -d name refuses to delete a branch with unmerged commits and -D forces it. That safety check is what makes bulk cleanup low-risk: list the merged branches, remove the ones you want to keep from the list, and feed the rest to git branch -d.

Bash Delete all merged branches except the protected ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The pipeline reads like a sentence. git branch --merged main lists merged branches; grep -v drops the current branch (the line starting with *) and the two names we want to protect; xargs -r git branch -d deletes what remains (-r means "do nothing if the list is empty"; it is GNU xargs, and on macOS you can leave it out). wip survived because it was not in the merged list. Even if a wrong name had slipped through, -d would have refused to delete a branch with unique commits.

Always protect your long-lived branches (main, develop, release/*) in the grep -v pattern. A branch that has nothing new can look "merged" and be deleted by a careless cleanup script, which is annoying when everyone else's branch started from it.

Finding stale branches

For branches that are not merged, the question becomes "is anyone still working on this?" Sort by last activity:

Bash List branches by most recent commit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git for-each-ref is the scripting-friendly tool behind many branch listings; --format picks fields such as %(refname:short), %(committerdate:short) and %(authorname). A branch whose last commit is months old and which is not merged is a candidate for a conversation, not for automatic deletion: ask the author, or archive it as a tag (git tag archive/old-idea old-idea and then delete the branch) so the commits keep a name.

Tracking branches

So far all branches were local. A remote is another copy of the repository, often on GitHub; Remotes covers it in depth. Branches on the remote are mirrored locally as remote-tracking branches with names like origin/main. You cannot commit to those; they are read-only bookmarks that Git updates when you fetch.

A tracking branch (also called a branch with an upstream) is a normal local branch configured to know its remote counterpart. The link is stored in .git/config, and it lets Git say how far ahead or behind you are and lets git push and git pull work without arguments. We can build a remote entirely on this machine using a bare repository (one without a working directory), which is how server-side repositories look.

Bash Upstream tracking: ahead, behind and branch -vv

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git branch -vv prints, for each branch, the commit, the upstream in square brackets and a status. The first time, Alice is [origin/main: ahead 1]: she has one commit the server lacks. After Bob pushes and Alice fetches, it reads [origin/main: ahead 1, behind 1], which means the histories have diverged and she will need to merge or rebase before she can push. git status -sb prints the same information in its first line (## main...origin/main [ahead 1, behind 1]). Fetch never changes your own branches; it only moves origin/main. We use git push -u (--set-upstream) once to create the link; the details of pushing are in push, pull and Tracking Branches.

You can set or change an upstream later with git branch -u origin/main (or git branch --set-upstream-to=origin/main) and remove it with git branch --unset-upstream. Creating a local branch from a remote one sets the link automatically: git switch feature (when only origin/feature exists) creates feature tracking it.

Pruning stale remote branches

When a teammate merges a pull request, the platform usually deletes the branch on the server. Your repository still has the old origin/their-branch bookmark, so git branch -r keeps listing branches that no longer exist. Pruning deletes those stale remote-tracking references. It never touches your local branches or any commits.

Bash Prune remote-tracking branches that vanished on the server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git push origin --delete topic removes the branch on the server (we ran it from a second clone to imitate a teammate). The first clone, dev, still lists origin/topic until you run git fetch --prune, which prints - [deleted] (none) -> origin/topic. Make this automatic once and forget it: git config --global fetch.prune true. A related command, git remote prune origin, prunes without fetching.

Be aware that pruning removes only the remote-tracking reference. Your local branch topic (if you had one) stays, and git branch -vv marks it [origin/topic: gone], which is your cue that the work was merged or abandoned upstream and the local branch can be deleted.

How long should a branch live?

Policies differ, but experience gives a rule of thumb:

  • Short-lived branches (hours to a few days) hold one feature or fix. They merge quickly, conflict rarely and are easy to review. Most branches should be like this.
  • Long-lived branches (main, develop, release branches such as release/2.4) exist on purpose and are protected. Keep their number small.
  • Stale branches are the problem: old, unmerged, often forgotten. Review and remove them regularly, for example monthly.

A branch that lives for weeks diverges from main and makes the final merge painful. If a feature is big, break it into pieces that can each be merged, hiding unfinished work behind a feature flag. The workflows that teams build around this idea (trunk-based development, Gitflow) are compared in Collaboration Workflows.

Branch protection

Hosting platforms (GitHub, GitLab, Bitbucket) let administrators protect branches such as main: no direct pushes, no force-pushes, no deletion, required reviews and passing checks before merging. This is configured on the server, not in Git itself, so you cannot try it in a local sandbox. Protecting the main line means a mistaken git push --force or an accidental delete is rejected for everyone. Pair it with a naming scheme (feature/*, release/*) so rules can target patterns. You can add a local safety net too, with a hook that blocks commits straight to main.

Pitfalls professionals know

  • git branch -D is the only common way to lose work by deleting a branch. Prefer -d; if you used -D in error, the reflog usually has the tip.
  • Deleting the remote branch is a separate act from deleting the local one: git branch -d x and git push origin --delete x.
  • Merged is not the same as safe to delete if others still use it. Check that nobody based new work on the branch.
  • Do not rename a branch others share without telling them. After git branch -m old new you also have to update the remote and every teammate's upstream.
  • Detached or stray leftovers (tags you forgot, stashes) are not branches. git branch only shows branches.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does git branch --merged main list?

    --merged lists branches whose tip is reachable from main, so deleting them loses nothing. Squash-merged branches usually do not appear because their commits are not in main's history.
  2. 2. Why is git branch -d safer than -D for cleanup?

    -d checks that the branch is merged and fails otherwise. -D deletes regardless and can leave commits with no name pointing at them.
  3. 3. What does [origin/main: ahead 1, behind 1] in git branch -vv mean?

    Ahead and behind at the same time means both sides have new commits, so you must merge or rebase before pushing.
  4. 4. What does git fetch --prune do?

    Pruning only deletes stale references such as origin/topic. Local branches and commits stay untouched.
  5. 5. Which command sets the upstream of the current branch to origin/main?

    git branch -u (--set-upstream-to) links the current local branch to a remote-tracking branch so push, pull and status know about it.

Summary

  • A branch is merged when its tip is contained in another branch; git branch --merged main and --no-merged main tell you which is which.
  • Delete with git branch -d (safe) in bulk by piping the merged list, minus protected branches, into xargs; avoid -D unless you mean it.
  • Squash and rebase merges hide "merged" status from Git; use your platform's pull-request status.
  • A tracking branch links a local branch to an upstream; git branch -vv and git status -sb show ahead/behind counts.
  • git fetch --prune (or fetch.prune true) removes stale remote-tracking branches; a local branch marked gone can be deleted.
  • Keep branches short-lived, review stale ones regularly, and protect long-lived branches on the server.

Next: Tags and Releases