Edit the Last Commit

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Git is a powerful version control system that allows developers to track changes made to their codebase. One of the most common tasks when working with Git is to edit the last commit. This can be useful when you need to make small changes to a commit that you have already made.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git/BasicOperationsGroup -.-> git/commit("`Create Commit`") subgraph Lab Skills git/commit -.-> lab-12767{{"`Edit the Last Commit`"}} end

Edit the Last Commit

You have just committed some changes to your Git repository, but you realize that you forgot to include a file or make a small change. You don't want to create a new commit just for this small change, but you also don't want to change the commit message. How can you edit the last commit without changing its message?

To demonstrate how to edit the last commit, let's use the repository from https://github.com/labex-labs/git-playground.

  1. Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. Realize that you forgot to include a file or make a small change. Add the text "New content" to the end of the README.md file. Add any staged changes to the last commit, without changing its message:
echo "New content" >> README.md
git add README.md
git commit --amend --no-edit
  1. Verify that the last commit now includes the changes you made:
git show HEAD

This is the content of the late commit:

Summary

Editing the last commit is a common task when working with Git. By using the git commit --amend --no-edit command, you can add any staged changes to the last commit without changing its message. This can be useful when you need to make small changes to a commit that you have already made.

Other Git Tutorials you may like