# git: how to rename a branch (both local and remote)?

To rename a branch in Git, you'll need to follow a series of steps to rename it locally and then update the remote repository to reflect the new branch name. Here’s how you can rename a branch both locally and remotely:

### Rename Branch Locally

1. **Switch to the Branch You Want to Rename:**
First, ensure you are on the branch that you want to rename. Use `git checkout` to switch to the branch:
    
    ```bash
    git checkout old-branch-name
    ```
    
2. **Rename the Branch:**
Rename the current branch to a new name using `git branch -m` (short for `git branch --move`):
    
    ```bash
    git branch -m new-branch-name
    ```
    
    Replace `new-branch-name` with the desired new name for your branch.
    

### Push the Renamed Branch to Remote

1. **Delete the Old Remote Branch:**
To delete the old branch from the remote repository:
    
    ```bash
    git push origin --delete old-branch-name
    ```
    
    Replace `old-branch-name` with the old name of your branch.
    
2. **Push the Renamed Branch:**
Push the renamed branch to the remote repository using the `u` option to set up the upstream branch:
    
    ```bash
    git push origin -u new-branch-name
    ```
    
    This command pushes the renamed branch (`new-branch-name`) to the remote repository and sets it as the upstream branch so that future `git pull` and `git push` commands work without specifying the branch name.
    

### Update Local Tracking Branch (if needed)

If you have other local repositories that have the old branch name as a tracking branch, you might want to update them:

```bash
git fetch --all --prune
```

This command fetches all branches from the remote repository and prunes any remote-tracking branches that no longer exist on the remote. This ensures that your local tracking branches are updated.

### Example Scenario

Let's say you want to rename `old-branch` to `new-branch`:

```bash
# Switch to the branch you want to rename
git checkout old-branch

# Rename the branch locally
git branch -m new-branch

# Delete the old remote branch
git push origin --delete old-branch

# Push the renamed branch to the remote repository
git push origin -u new-branch
```

### Notes

- **Collaboration:** Renaming a branch affects its history and can cause issues for collaborators who have checked out the old branch. Communicate with your team before renaming branches to avoid confusion.
- **History:** Renaming a branch does not change its commit history; it only changes the branch name and its references.

By following these steps, you can safely rename a Git branch both locally and on the remote repository, ensuring consistency and clarity in your branch naming conventions.