DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Tidy Up Your Git: A One-Liner for Deleting Merged Branches

Introduction

Working with Git, especially when frequently creating feature branches, can lead to a convoluted branch system. As the number of branches increases, manually deleting each one becomes a daunting task. In this post, I'll walk you through a way to delete merged Git branches in bulk and how to set up an alias for it in a Zsh environment.

Requirements

  • Git installed
  • Zsh installed (needed for the alias setup part)

Deleting Branches

Let's start with the command to display merged branches:

git branch --merged
Enter fullscreen mode Exit fullscreen mode

This command lists the branches that have been merged into the current branch.

Next, we exclude the master branch or any other branches you want to retain from this list, and delete the remaining branches. The command below excludes the master and develop branches and deletes the remaining merged branches:

git branch --merged | egrep -v "(^\*|master|develop)" | xargs git branch -d
Enter fullscreen mode Exit fullscreen mode

Here, egrep -v "(^\*|master|develop)" excludes the current branch (indicated by *), master branch, and develop branch from the list of merged branches. If you have other branches you want to keep, add their names here.

Finally, xargs git branch -d runs the git branch -d command (branch deletion command) for each of the filtered branches.

Setting Up Alias in Zsh

Setting up these series of commands as an alias lets you delete merged branches by typing just one command. This can prevent typos and save you typing time.

To set up an alias in the Zsh environment, add the following line to your ~/.zshrc file:

alias delete_merged_branches="git branch --merged | egrep -v \"(^\*|master|develop)\" | xargs git branch -d"
Enter fullscreen mode Exit fullscreen mode

After saving this configuration, either start a new terminal session or execute the following command to reflect the changes in the ~/.zshrc file:

source ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Now, when you run the delete_merged_branches command in the terminal, it will delete the merged branches.

Things to Note

When deleting branches in Git, exercise caution. The deletion operation cannot be undone, so confirm that the branches you are deleting are truly no longer needed before you proceed. Also, note that this command deletes local branches. To delete remote branches, you need to execute git push origin --delete <branch_name> specifying the branch name.

Conclusion

In this post, we went over how to delete merged Git branches in bulk and how to set up an alias for the operation in a Zsh environment. This should make managing your branches easier and your development workflow more efficient. Happy Git-ing!

Top comments (0)