Additional Tips

  • Remote Branches: If you also want to clean up remote branches that have been merged, you’ll need to fetch and then delete remote branches. However, this should be done with care and coordination with your team.
  • Dry Run: Always consider running a dry run (just listing the branches) before actually deleting them to avoid accidental deletions.
  • Backups: Ensure you have pushed all necessary branches and changes to the remote repository or have backups before deleting any branches.

How to Delete all Git Branches which have been Merged?

To delete Git branches that have been merged into the current branch, you can use a combination of git branch and git branch -d commands along with some scripting. Below is a step-by-step guide:

Table of Content

  • Switch to the Branch You Want to Clean Up
  • List Merged Branches
  • Delete Merged Branches
  • Force Delete (if necessary)
  • Confirmation
  • Additional Tips

Similar Reads

Switch to the Branch You Want to Clean Up

Before you start cleaning up merged branches, ensure you’re on the branch from which you want to remove the merged branches. Typically, this is the main development branch, such as master or main....

List Merged Branches

Use the git branch –merged command to list branches that have been merged into the current branch. This command will list all branches that have been merged into the current branch....

Delete Merged Branches

You can delete the merged branches listed in the previous step using a loop in Bash or another scripting language. Below is an example Bash script to achieve this:...

Force Delete (if necessary)

If some branches cannot be deleted with the standard -d option because they contain unmerged changes (which is unlikely if they are listed as merged), you can use the -D option to force delete them. Use this with caution....

Confirmation

After running the script, Git will prompt you to confirm the deletion of each branch. Press y and Enter to confirm the deletion of each branch....

Additional Tips

Remote Branches: If you also want to clean up remote branches that have been merged, you’ll need to fetch and then delete remote branches. However, this should be done with care and coordination with your team. Dry Run: Always consider running a dry run (just listing the branches) before actually deleting them to avoid accidental deletions. Backups: Ensure you have pushed all necessary branches and changes to the remote repository or have backups before deleting any branches....