Updating a Git commit


Amend

Updating the most recent commit is very simple with amend:

$ git add . # stage changes
$ git commit --amend

This will open the editor with the option to modify the commit message.

If you want to keep the same commit message and not open the editor:

$ git commit --amend --no-edit

With amend, you can even change metadata information like the author and/or date:

$ git commit --amend --author="Name <[email protected]>"

Rebase

If the commit is not recent, then you want to use rebase.

First, you’ll want to list out the commits to be interactively rebased:

$ git rebase -i HEAD~3 # last 3 commits from HEAD

A hash is also accepted:

$ git rebase -i hash123^ # commits from hash123 to HEAD

The editor will open and change pick to edit for the commit(s) you plan to modify.

Then amend the commit(s) and continue:

$ git commit --amend
$ git rebase --continue

If merge conflicts arise, resolve them. Keep going until the rebase is finished.

Otherwise, you can abort it if you changed your mind or made a mistake:

$ git rebase --abort

One final note, if the commits are already pushed to a remote branch, it’s advisable not to amend them becase a force push is required to update the branch, which will cause conflicts for collaborators.