Git

How to Cancel a Local Git Commit?

Git commit is used to save/push the staged changes to the remote repository. While working on a Git project, developers make several changes and save them. Sometimes, they make changes and commit them that cause some problems later. So, it can be required to revert that specific commit to go back to the previous state. For this corresponding purpose, Git allows them to cancel any local commits.

This article will demonstrate the method to delete a local commit in Git.

How to Cancel a Local Git Commit?

To cancel a local Git commit, first, switch to the local repository and make some changes to it. Then, run the “git reset HEAD” command to revert those changes. Lastly, check the Git log to verify changes.

To do so, try out the following steps.

Step 1: Switch to Desired Repository

First, redirect to the local Git directory through the given-below command:

$ cd "C:\Git\Repo2"

 
Step 2: Check Git Log

Then, check the commit history to view all the commits that have been made in the repository:

$ git log --oneline

 
In below-screenshot, it can be seen that the HEAD is pointing to the “FileC modified” commit:


Step 3: Create a New File

Next, make a new file in the current repository using the “touch” command:

$ touch test.txt

 

Step 4: Stage File

To add the file to the Git staging area, run the “git add” command along with the file name:

$ git add test.txt

 

Step 5: Commit Changes

After that, save the staged changes to the local repository:

$ git commit -m "test file added"

 

Step 6: View Commit History

Next, check the Git log to view the current position of HEAD:

$ git log --oneline

 
It can be observed that the HEAD is now pointing to the new “test file added” commit:


Step 7: Delete Git Commit

In order to delete the previous commits, utilize the “git reset” command and specify the number of commits:

$ git reset HEAD~1

 
Here, “HEAD~1” is used to reset the last commit:


Step 8: Verify Changes

Lastly, ensure whether the commit has been deleted or not by checking the Git log:

$ git log --oneline

 
According to the below output, the previous commit has been deleted and now the HEAD is again pointing to the “FileC modified” commit:


This article demonstrated the procedure to cancel the local Git commit.

Conclusion

In order to cancel a local Git commit, first, redirect to the Git local repository. Then, add some changes to it. Next, run the “git reset HEAD” command to revert those changes. Lastly, check the Git log to ensure the latest changes. This article demonstrated the method to delete a local commit in Git.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.