[Git] How to rename remote branches and commits
by Riley MacDonald, January 15, 2018

When working with git and an issue tracking system I always prefix my commits with the issue tracker number. This makes the history much easier to navigate in the future. Sometimes I make a mistake and push a branch or commit to the remote with the wrong information. Here’s how I handle these scenarios.

Renaming a branch on the remote
You can rename a branch with this command. Note: If you have a pull request open under this branch on GitHub it will be closed without warning when executing this command:

# Example: git push [remote] [remote]/[old_name]:refs/heads/[new_name] :[old_name]
$ git push origin origin/oldBranch:refs/heads/newBranch :oldBranch
 
Total 0 (delta 0), reused 0 (delta 0)
To git.somewhere.com:Org/Project.git
 - [deleted]         oldBranch
 * [new branch]      oldBranch -> newBranch

Sweet, the branch has been renamed. Make sure to remove the old local branch to avoid confusion:

$ git branch -D oldBranch

Renaming the last commit pushed to the remote
Renaming commits is easier than branches. Just use the --amend argument:

$ git commit --amend

This will pop your preferred text editor. Edit the commit message as desired and save. Now you’ll be in a bit of a conflicted state as the local and remote aren’t agreeing:

$ git status
 
Your branch and 'origin/newBranch' have diverged,
and have 1 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)
 
nothing to commit, working tree clean

Note: This is a potentially destructive command! This command can destroy data if used incorrectly. If you’re working on a branch with other developers I don’t suggest using it. Since I’m the only dev and I’m positive I’ve only modified the commit message I chose to use it:

git push --force origin newBranch

Summary
Success, my branch name and commit message are now as desired. My history will be clean moving forward.

Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

Be the first to leave a comment on this post!