Managing Merged Git Branches

Git is a powerful version control system that allows developers to manage different versions of their codebase. One common task when working with Git is deleting branches that have already been merged into the main branch. In this tutorial, we will explore how to delete all merged Git branches at once, both locally and remotely.

Listing Merged Branches

To start, you need to list all the branches that have been merged into the current branch. You can do this using the git branch command with the --merged option:

git branch --merged

This will show you a list of all the local branches that are fully merged into the currently checked out branch.

Excluding Important Branches

You might not want to delete certain important branches, such as master, main, or dev. To exclude these branches from the list, you can use the grep command:

git branch --merged | grep -Ev "(^\*|^\+|master|main|dev)"

This will exclude the current branch (*), any branch checked out in another worktree (+), and the specified branches (master, main, and dev).

Deleting Merged Branches

Once you have the list of merged branches, you can delete them using the git branch -d command. To delete all the merged branches at once, you can pipe the output of the previous command to xargs:

git branch --merged | grep -Ev "(^\*|^\+|master|main|dev)" | xargs --no-run-if-empty git branch -d

This will delete all the local merged branches except for the excluded ones.

Deleting Remote Merged Branches

To delete remote merged branches, you can use a similar approach. First, list all the remote branches that are fully merged into the current branch:

git branch -r --merged

Then, exclude the important branches and pipe the output to xargs with the git push --delete command:

git branch -r --merged | grep -v '\*\|master\|main\|develop' | sed 's/origin\///' | xargs -n 1 git push --delete origin

This will delete all the remote merged branches except for the excluded ones.

Syncing Local and Remote Branches

After deleting remote branches, you can sync your local registry of remote branches using:

git fetch -p

or

git remote prune origin

This will remove any local references to deleted remote branches.

Creating a Git Alias

To make it easier to delete merged branches in the future, you can create a Git alias. Add the following line to your Git configuration file (usually ~/.gitconfig):

[alias]
    cleanup = "!git branch --merged | grep  -v '\\*\\|master\\|develop' | xargs -n 1 -r git branch -d"

Then, you can delete all the local merged branches by running:

git cleanup

Conclusion

In this tutorial, we have learned how to delete all merged Git branches at once, both locally and remotely. We have also seen how to exclude important branches from deletion and how to sync our local and remote branch registries.

Leave a Reply

Your email address will not be published. Required fields are marked *