How to edit git commit?

Git commit command records the repository changes, we can give a message while committing changes. Sometimes we may need to edit the last commit. In this article, we will discuss the methods to edit commit.

To add the git commit message we will use the following command

git commit -m message

Possible scenarios to edit the last commit

  • To change the commit message
  • To change the actual content of the commit by adding, removing and modifying files

1.Changing the commit message

Suppose we have a test repository with two commits but the commit message(“Updat”) is not correct.

To edit the last commit message run the following command. Updated commit message as shown below.

git commit --amend -m new message
git commit --amend -m "Updated readme file"

2.Change the content of the commit

When you commit too early and possibly forget to add some files. Suppose we want to add the “help.txt” file to the last commit, we can add it using the following commands.

git add help.txt
git commit --amend

In conclusion, the following points to note

  • Under the hood “git commit –amend” takes staging area for commit.
  • The obvious use of “git commit –amend” is to update last commit without cluttering your respository history with commit messages like “Oops forgot to add file”,”Fixing typo in the last commit message”.
  • Only amend commits that are still in local. Amending previously pushed commits and force pushing the branch will cause problems for your collaborators.

To read about unmodify files,unstaging files please read our article.

Leave a Comment