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 More
Git Branch Renaming: How to Safely Modify Local and Remote Branch Names

This article introduces methods for renaming Git branches, with the core being handling local branches first and then safely updating remote branches. Renaming a local branch is straightforward: first switch to another branch (e.g., `main`), execute `git branch -m oldbranch newbranch`, and verify. For remote branches, proceed with caution using the following steps: 1. Pull the latest code of the old branch (`git checkout oldbranch && git pull`); 2. Create and push a new branch (`git checkout -b newbranch && git push origin newbranch`); 3. Delete the remote old branch (`git push origin --delete oldbranch`); 4. Clean up the local old branch (`git branch -d oldbranch`) and tracking branches (`git fetch --prune`), then switch to the new branch. Verification can be done using `git branch` and `git branch -r`. Precautions include: notifying the team before renaming, ensuring uncommitted changes are addressed, having permissions to delete remote branches, and updating CI/CD pipelines for protected branches. The core principle is to first copy remote branches to new ones before deleting old ones to avoid collaboration conflicts.

Read More