How to add changes to an old commit?

We can change the latest Git commit by simply using the git commit --amend command. But what if you want to change an older commit (not the latest one)? And why would you want to do that?

When I’m working on my code in a local branch, I always try to focus on one type of change and group them into atomic commit. For example changes in some business logic should be separated from a gem upgrade. From time to time I need to update an older commit with a required change that fits perfectly into that older commit but I didn’t notice it before I added a new commit.

Here are the commands I use to make a change to an old commit, without changing the commit message of the old commit. OLDCOMMIT is a hash of the commit I want to change (something like 35d1083). It helps me to keep my git history clean as I do not need to add another commit just to add some missing changes.

git add <fixed files>
git commit --fixup=OLDCOMMIT
git rebase --interactive --autosquash OLDCOMMIT^

It works perfectly in a scenario where the next commits (after the OLDCOMMIT) haven’t introduced any changes in the code/file you want to change (there will be no conflicts). If some changes where added in meanwhile make sure to checkout and fix the version of the file from the commit you want to change (not the current one).

Note that rebasing changes the history (hashes) of the updated commit (OLDCOMMIT) and all subsequent commits. It is not recommended to rebase commits that have already been pushed to the repository. Please do not do that!