Amending git commits

Git is a wonderful SCM with some very powerful features. But as a programmer, it’s very easy to aquire a rudimentary working knowledge of Git and never learn anything more. For example, how would we fix our repository if we committed the wrong piece of code? What if our commit had an error in it? How do we fix things without reverting or introducing a second commit?

It turns out this is very easy to do. The latest versions of Git have an amend command. Amend lets us alter the last commit we made. All that’s necessary is for us to arrange our working directory the way we want the last commit to look and then execute:

git commit --amend

This will update the most recent commit based on the state of our working directory. For example, say we changed our README file in the last commit and accidentally introduced a typo. To fix the last commit, we would edit the README again, git add the change, and instead of running git commit which would create a second commit, we run git commit --amend which patches the last commit. This can be repeated as many times as necessary.

Note that rewriting history like this can have serious implications if you’ve already published the most recent commit. But if you’re the only developer using the repository, or if you haven’t published yet, this can be a great way to fix minor mistakes without introducing an entirely new commit.

You can read more about amend in the documentation.

One thought on “Amending git commits

Comments are closed.