Code Premix

How to undo a Git commit that hasn’t been pushed

šŸ“…July 19, 2022
šŸ—Git

Today we will show you how to undo a Git commit that hasnā€™t been pushed in Git remote repository. Weā€™ll provide you the three different ways to undo commit which has not been pushed.

Example

In this article, we will create an example to show you a demo. Letā€™s assume that we have created a project repository and create a new file called file1.txt. Also write some text in this file.

Run the git status command to see the output.

git add file1.txt
git commit -m ā€œfirst commitā€

Check out the following screen after executing the above commands.

Ways to undo commit before push in Git

  1. Undo commit and keep file staged
  2. Undo commit and unstage file
  3. Undo commit and discard changes

1. Undo commit and keep file staged

Letā€™s say if we want to undo the commit but keep all files staged then we should use the following command.

git reset --soft HEAD~1

Most of the time we should use this command to update the committed message without touching the file.

2. Undo commit and unstage file

If you want to undo the last commit and unstage all files then you can use the below command.

git reset HEAD~1

3. Undo commit and discard changes

In case you want to undo commit and discard all changes or in other words we can say hard reset the index and working tree then use the following command.

git reset --hard HEAD~1

Note: To change the commit message check out the article: How to change the commit message in git.

Thatā€™s it for today.
Thank you for reading. Happy Coding..!!