Git: how to revert changes that are committed but not pushed

When you work under git project, you might have faced a situation that you accidently committed that changes. But before pushing those changes to git, you realized that

“Oops! That wasn’t suppossed to be committed”

But the good news is that, In Git, it is possible to revert the changes that you have committed but not pushed yet. Below are the different ways to achieve it:


1. Modify The Most Recent Commit:

This is useful when you want to fix the most recent commit like changing the commit message or forgot to add a file.

git commit --amend

This will open your configured editor and open any staged changes into the same commit.

Example:

git add .
git commit -m "Initial Commit"

#Here you realize that you missed the file
#So you add the file and use git --amend
git add my-file.txt
git commit --amend

2. Undo the Last Commit but Keep the Changes

This option will be helpful when you want to revert all your commit and the code is still needed.

git reset --soft Head~1

This command will remove the last commit and keep your changes staged.

Example:

git add .
git commit -m "Initial Commit"

#Here you realize that you want to make some changes before push
# so you use below command
git reset --soft Head~1

3. Undo Commit and Unstage Changes

This will be helpful when you want to revert the commit, keep the changes locally and start with fresh commit.

git reset --mixed Head~1

This command will remove the changes and keep your changes into your local directory unstaged. This is the default behavior of git reset.

git reset Head~1

4. Revert commit and Discard Changes Completely

This will be helpful when you want to revert the last changes and discard all of your changes that you made as a part of that commit. Please be very careful while using this command. Because once it is reverted, it cannot be undone.

Git reset --hard Head~1

5. Revert the Commit using Git Revert

This is one of the safest option. Becuase It will not alter the history of your commits. But it will revert the changes of your previous commit and push new changes.

git revert Head

Home ยป Git: how to revert changes that are committed but not pushed

Leave a Comment