Advanced Git Branch Management: Sorting, Pruning, and Deleting Branches

Difficulty: advanced
Est. Time: 60 minutes
Prerequisites:
  • Mastering Git Submodules and Hidden Features
Advanced Git Branch Management: Sorting, Pruning, and Deleting Branches
15 min
TUTORIAL
git
branches
pruning
deleting
advanced

Advanced Git Branch Management: Sorting, Pruning, and Deleting Branches

Managing branches effectively is crucial for maintaining a clean and organized Git repository. Over time, repositories can accumulate many branches, making it challenging to keep track of active, merged, or stale branches. In this advanced blog, we’ll explore how to sort, prune, and delete branches (both locally and remotely) effectively.

Table of Contents

  • Sorting Branches
  • Pruning Stale Branches
  • Deleting Local and Remote Branches
  • Useful Scripts for Branch Views
  • Exercise: Mastering Branch Management

Sorting Branches

Sorting branches helps you organize them based on criteria like date, name, or merge status:


  # Sort by most recent commit
  git branch --sort=-committerdate
  
  # Sort alphabetically
  git branch --sort=name
  
  # Filter merged or unmerged branches
  git branch --merged
  git branch --no-merged
          

Pruning Stale Branches

Pruning removes references to remote branches that no longer exist on the remote repository:


  # Dry run to preview stale branches
  git remote prune origin --dry-run
  
  # Prune remote-tracking branches
  git remote prune origin
  
  # Automate pruning during fetch
  git config --global fetch.prune true
          

Deleting Local and Remote Branches

Deleting branches ensures your repository remains clutter-free:


  # Delete a local branch
  git branch -d <branch-name>
  
  # Force delete a local branch
  git branch -D <branch-name>
  
  # Delete a remote branch
  git push origin --delete <branch-name>
  
  # Bulk delete merged branches
  git branch --merged main | grep -v "main" | xargs git branch -d
          

Useful Scripts for Branch Views

Visualize branches and automate cleanup with these scripts:


  # Visualize branches with a graph
  git log --oneline --graph --all
  
  # List active branches sorted by activity
  git branch --sort=-committerdate --format='%(refname:short) %(committerdate:relative)'
          

Exercise: Mastering Branch Management

Practice branch management:

  • List all branches sorted by the most recent commit.
  • Identify branches that have been merged into main.
  • Perform a dry run to preview stale branches and prune them.
  • Delete a local branch that has been merged and a remote branch that is no longer needed.
  • Use visualization tools like git lg to explore branch relationships.

Coming Up Next

In the next part of this series, we’ll dive deep into git reflog, exploring how it acts as a safety net for recovering lost commits and understanding its role in disaster recovery.

Part 14 of 24 in Git Mastery Series: From Beginner to Expert
All Posts in This Series