Sometimes I have a few local git commits that are yet to be pushed. Occasionally when this happens, I realise that one of those commits is broken (e.g. I forgot to include something in it). In such cases the following is a useful means of editing a previous commit.
WARNING: Attempting to do this for a commit that has been shared with others (e.g. by pushing to Github) may cause serious injury or death (ok, probably not, but it might cause a bit of upset).
If you have the changes to apply in your work area, stash them now.
Identify the commit before the one to be amended (you'll need its commit hash). Use a tool such as GitX (L) if you like (or you can just use git-log).
Run git-rebase:
git rebase -i <commit-hash>
This will bring up an edit window (in vim on my machine). Each commit after the one identified by <commit-hash>
will be listed and will be initially prefixed by pick
. For the commit you want to amend, change pick
to edit
. Save and exit (i.e. :wq
in vim).
Make the required amendments to the commit (e.g. git stash apply
if those changes had been stashed).
git add -p
to stage those changes.
git commit --amend
to amend the commit.
git rebase --continue
to apply any subsequent commits.
Et voila, your commit history has been updated!
Simples.