Git Branch Renaming: Steps to Safely Modify Local and Remote Branch Names
### Guide to Renaming Git Branches Renaming branches is necessary to improve code structure clarity due to early naming inconsistencies, collaboration requirements, or logical adjustments. Ensure no uncommitted changes exist locally (`git status` for verification) and notify the team to avoid conflicts before proceeding. **Renaming a Local Branch**: Execute `git branch -m old_branch_name new_branch_name`, e.g., `git branch -m dev_old dev`. Verify with `git branch`. **Renaming a Remote Branch**: Since Git does not support direct renaming, follow these steps: ① Delete the remote old branch (`git push origin --delete old_branch_name`; irreversible, confirm content first); ② Push the local new branch (`git push origin new_branch_name`); ③ Optionally set upstream tracking (`git branch --set-upstream-to origin/new_branch_name`). Verification: Check remote branches with `git branch -r` and switch to test the new branch. **Notes**: Synchronize with the team when working collaboratively, rename after merging, and back up remote branches before deletion.
Read MoreGit 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