How to modify staged (existing/unpushed) commit(s) in Git?


Modify previous staged commit

git commit --amend

Modify previous staged commit with new message

git commit --amend -m "Updated commit message"

Modify any previous commit message

git rebase --interactive $parent_of_flawed_commit


Modify Staged Commit And Push To Remote

  1. This command will pen your editor, allowing you to change the commit message of the most recent commit.
git commit --amend

This command lets you set the commit message directly in the command line with:

git commit --amend -m "Updated commit message"

Make sure you don’t have any working copy changes staged before doing this or they will get committed too. (Unstaged changes will not get committed.)

  1. If you’ve already pushed your commit up to your remote branch, then you’ll need to [force push]() the commit with
git push --force <remote> <branch>  # Force push
git push -f <remote> <branch>       # Shorter

Modify Multiple Previous Local Commits

  1. If you want to fix several flawed commits, pass the parent of the oldest one of them.
git rebase --interactive $parent_of_flawed_commit  # Interactive
git rebase -i $parent_of_flawed_commit             # Shorter
  1. An editor will come up, with a list of all commits since the one you specified in $parent_of_flawed_commit.
  2. Change pick to reword (or on old versions of Git, to edit) in front of any commits you want to fix.
  3. Once you save, Git will replay the listed commits.

  4. For each commit you want to reword, Git will drop you back into your editor. For each commit you want to edit, Git drops you into the shell. If you’re in the shell:

# Change the commit in any way you like.
git commit --amend
git rebase --continue

Most of this sequence will be explained to you by the output of the various commands as you go. It’s very easy, you don’t need to memorize it – just remember that git rebase --interactive lets you correct commits no matter how long ago they were.