Git Repository Cleanup: Methods to Delete Unused Local and Remote Branches
The article introduces the necessity, steps, and precautions for cleaning up useless Git branches. Necessity: reducing repository clutter, lowering the risk of accidental deletion, and saving storage space. Before cleaning, confirm permissions, check branch status (whether merged), and back up important branches. For local deletion: First, list branches with `git branch --merged main_branch` to filter merged branches. After confirmation, delete merged branches with `git branch -d branch_name`, and use `-D` for unmerged branches (high risk). For remote deletion: Directly delete remote branches with `git push origin --delete branch_name`, or use `git fetch -p` to clean up locally tracked remote obsolete branches. Advanced tips: Batch delete merged branches locally using `git branch --merged master | grep -v '^\*\|master\|main' | xargs git branch -d`, and similar looping commands for remote branches. Precautions: Confirm if branches are in use by others, avoid deleting unmerged branches by mistake, and note that recovery is difficult after deletion. When regularly cleaning, confirm status first to ensure safety and efficiency.
Read More