Rewrite an older commit with rebase and stash

You just commited some modifications, but there you’ve to edit things that are related to a previous commit, which isn’t the last one. So, instead of simply amending the commit, you need some more work to keep clean commits.

Assume you’ve the following commit log:

commit 1e227021e414f25b664a4388142f1db580df7649
Author: XX
Date:   Wed May 25 17:39:21 2016 +0200


commit 3bf53233d053463931124bae5b81490733c1fb4a
Author: XX
Date:   Tue May 24 18:14:29 2016 +0200


Now you just fixed something related to the commit “First” (here 3bf5323), it’d be cleaner if this modification could be added to the “First” commit.

Edit some files, and then stash your current modifications.

git stash 

Rebase from the commit you want to edit:

git rebase -i HEAD~2 #rebase from two commits upon HEAD

Just use “edit” on the commit you want to amend, for example:

edit 3bf5323 First
pick 1e22702 Second

Now rebasing should stop on 3bf5323, you can apply the stash and commit as usual:

git stash apply
git add [somefile]
git commit --amend

Just continue the rebase, resolve conflicts if needed:

git rebase --continue

It’s done, your history is the same, but the modification happened on the HEAD~2.

You might need to force push the branch if you already pushed the commits: git push -fu origin mybranch.