Cleaning up merged Git branches

When working with Git, developers need to manage and collaborate on code efficiently, and version control is essential to achieve this goal. However, as a project grows, the number of Git branches increases, resulting in a cluttered and confusing repository. Merged branches that are no longer required can take up valuable space and hinder productivity. In this article, we will explore how to use a command to clean up merged Git branches.

To clean up merged Git branches, you can use the following command:

$ git branch --merged | egrep -v "(^\*|master|main|dev)" | xargs git branch -d

Let's break down the command and see how it works.

The git branch --merged command displays a list of all branches that have been merged into the currently checked out branch. However, this command includes branches that are not required, such as the main, master, or dev branches. So, we use egrep to filter out these branches.

The egrep -v "(^\*|master|main|dev)" command excludes the main, master, or dev branches and the currently checked out branch, which is represented by the asterisk symbol (*). This filter ensures that we only delete branches that have been merged and are not the primary development branches.

Finally, the xargs git branch -d command deletes all merged branches except for the main, master, or dev branches. The xargs command reads the output of the previous command and passes each line as an argument to the next command, which deletes the branch.

Using this command makes it easy to clean up merged Git branches quickly and efficiently. You can run this command regularly as part of their Git maintenance routine, ensuring that their repository stays organized and easy to navigate. It helps your Git repository remain tidy, organized, and optimized for efficient development.

Clicky