问题答案 12026年5月28日 07:50
How do I delete all Git branches which have been merged?
In daily software development, regularly cleaning up branches that have been merged into the main branch is a good practice to maintain a clean repository. To delete all branches that have been merged into the main branch, follow these steps:1. Determine the Name of the Main BranchFirst, ensure you know the name of your main branch. In most cases, this branch is named or .2. List All Merged BranchesYou can use the command to list all branches that have been merged into the current branch. If your main branch is , you may need to switch to the branch first:This command will list all branches that have been merged into .3. Delete Merged BranchesThen, iterate through these branches and delete each one (except itself). A common approach is to use the command to exclude the main branch, combined with and for deletion:If your main branch is , simply replace with in the above command.4. Important NotesSafety Check: Before executing deletion operations, verify that the branches listed by are indeed no longer needed.Remote Branches: The above commands handle local branches only. To delete remote merged branches, use a similar command:Here, identifies merged remote branches, and , , and work together to perform the deletion.5. ExampleSuppose I have several feature and fix branches in my project that have been merged into after completing the work. By following these steps, I can easily clean up these unnecessary branches and maintain a tidy Git repository.After executing these commands, both my local and remote repositories contain only the necessary branches, simplifying project version history management.