Changing your latest commit

In a nutshell: First make your changes. Then git add them. Finally, call git commit --amend to append the changes to your last commit.

Problem

  • You added a file notes in your last commit.
  • You realize you made a typo in notes file and want to add the correction to your last commit.

In this example, these are the contents of notes:

These are my notes. Dis is test data

Solution

Make your changes and stage them

Open notes in a text editor, change ‘Dis’ to ‘This’ and add the missing period. Save your changes. Mark the entire file for commit using git add notes. According to git diff --staged, the following changes are marked for commit:

diff --git a/notes b/notes
index b97c6c5..f2478b8 100644
--- a/notes
+++ b/notes
@@ -1 +1 @@
-These are my notes. Dis is test data
+These are my notes. This is test data.

Append the staged changes to your last commit

Run git commit --amend. Your commit editor will launch and show something like this:

Create note file

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Sat Mar 17 07:52:27 2018 +0100
#
# On branch master
#
# Initial commit
#
# Changes to be committed:
#	new file:   notes
#

You can edit the commit message if you wish. After saving and quitting, your git log will looks a bit this:

commit ad1d49c2b2771733cb14c90dda1b6f32d5ce60ea
Author: Pieter De Decker <[email protected]>
Date:   Sat Mar 17 07:52:27 2018 +0100

    Create note file with initial contents

git status should report a clean working directory now:

On branch master
nothing to commit, working tree clean