Back to posts
Keep X branches in git local

Keep X branches in git local

Mahmudul Hasan Nayeem / July 1, 2025

Managing branches in Git can sometimes become overwhelming, especially when you have multiple branches for different features or fixes. Keeping your local repository clean and organized is essential for efficient development. In this blog, we will explore how to keep only a specific number of branches in your local Git repository. for this example, we will keep only 2 branches in our local repository.

Step-by-Step: Keep Only 2 Local Branches

  • Suppose you want to keep:

    • main
    • feature-xyz

Step 1: Confirm branches you want to keep

First, check the branches in your local repository:

git branch

Let's say you see this:

dev
feature-abc
feature-xyz
hotfix-1
* main
feature-branch

You want to keep only main and feature-xyz.

Step 2: Delete all other local branches

Run this shell command to delete all except those two:

For Linux/macOS:

git branch | grep -v "main" | grep -v "feature-xyz" | xargs git branch -D

For Windows (PowerShell):

git branch | Where-Object {$_ -notmatch "main|feature-xyz"} | ForEach-Object {git branch -D $_.Trim()}

Notes:

  • This only affects local branches, not remote ones.
  • If you also want to clean up remote-tracking branches, you can run:
git fetch --prune
  • Always ensure you have pushed any important changes to the remote repository before deleting branches.

Conclusion

Keeping your local Git repository organized by limiting the number of branches can significantly enhance your workflow. By following the steps outlined above, you can easily manage your branches and focus on the most relevant ones for your current development tasks. Remember to always double-check which branches you are deleting to avoid losing important work.

0