Skip to content

Instantly share code, notes, and snippets.

@shakhmehedi
Created September 12, 2016 23:23
Show Gist options
  • Save shakhmehedi/98bcac1b8933c7e613f188888e7d18b2 to your computer and use it in GitHub Desktop.
Save shakhmehedi/98bcac1b8933c7e613f188888e7d18b2 to your computer and use it in GitHub Desktop.
Git Amend Old commit

Source stackoverflow.com
#Use the awesome interactive rebase:

git rebase -i @~9   # Show the last 9 commits in a text editor

Find the commit you want, change pick to e (edit), and save and close the file. Git will rewind to that commit, allowing you to either:

  1. use git commit --amend to make changes, or
  2. use git reset @~ to discard the last commit, but not the changes to the files (i.e. take you to the point you were at when you'd edited the files, but hadn't committed yet). The latter is useful for doing more complex stuff like splitting into multiple commits.

Then, run git rebase --continue, and Git will replay the subsequent changes on top of your modified commit. You may be asked to fix some merge conflicts.

Note: @ is shorthand for HEAD, and ~ is the commit before the specified commit.

Read more about rewriting history in the Git docs.

#Don't be afraid to rebase

ProTip™: Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:

$ git reset @~3   # go back 3 commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started
  • Watch out for options like --hard and --force though — they can discard data.
  • Also, don't rewrite history on any branches you're collaborating on.

On many systems, git rebase -i will open up Vim by default. Vim doesn't work like most modern text editors, so take a look at how to rebase using Vim. If you'd rather use a different editor, change it with git config --global core.editor your-favorite-text-editor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment