Correcting Commits in Git: The git commit --amend Command

Learn how to modify and correct your last Git commit using the git commit --amend command. This guide will explain the process and provide examples to help you effectively amend your commits.


Git - Commit Changes

tom has already committed his changes, but now he wants to correct his last commit. In this situation, the git commit --amend operation will help. This operation modifies the last commit, including the commit message, and creates a new commit ID.

Viewing the Commit Log

Before performing the amend operation, tom checks the commit log using the git log command:

Syntax

[tom@CentOS project]$ git log
Output

commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: tom Mouse <tom@tutorialsarena.com>
Date: Wed Sep 11 08:05:26 2013 +0530

    Implemented my_strlen function

commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialsarena.com>
Date: Wed Sep 11 07:32:56 2013 +0530

    Initial commit
        

Next, tom makes the necessary changes to the code, stages them, and then commits the new changes using the --amend operation:

Checking Status and Amending Commit

[tom@CentOS project]$ git status -s
M string.c
?? string

[tom@CentOS project]$ git add string.c

[tom@CentOS project]$ git status -s
M string.c
?? string

[tom@CentOS project]$ git commit --amend -m 'Changed return type of my_strlen to size_t'
[master d1e19d3] Changed return type of my_strlen to size_t
1 file changed, 24 insertions(+), 0 deletions(-)
create mode 100644 string.c

Now, tom checks the commit log again:

View Updated Commit Log

[tom@CentOS project]$ git log
Output

commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: tom Mouse <tom@tutorialsarena.com>
Date: Wed Sep 11 08:05:26 2013 +0530

    Changed return type of my_strlen to size_t

commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialsarena.com>
Date: Wed Sep 11 07:32:56 2013 +0530

    Initial commit
        

After the amend operation, the git log command shows the new commit message along with the new commit ID.