How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (2023)

In this article we will learn how we can undo acommitor multiplecommitsinGit. We will also look at how topushthese changes to theRemote Repository(Github) after we have undone the commit(s) in theLocal Repository.

To understand the concepts and examples used in this article, we have made a local repository synced with a remote repository on Github.

The repository consists of a single file -File 1.txt“.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (1)

There arefivecommits in the repository, and every preceding commit hasone extra lineentered into the file. The file content based on the commits is as follows -

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

We will refer to this table for all the examples used in this article.

We have used git bash in the examples for local repositories.

Let us look into the following topics -

Table of Content - git undo a commit
Use git reset HEAD to git undo a commit (recommended way)
Pushing the updated commits to Github after we git undo a commit.
Use git reset hard to git undo a commit (powerful but destructive)
Use git revert to git undo a commit (code gets reverted on the existing commits)

git reset HEAD- undo commit(s) in Git - (Recommended)

Sometimes we may come across a situation where we have made acommitor multiplecommits(by mistake or some other reasons) and then want toundothatcommit(s)and make thatcommit(s)disappear from thegit log.

git reset HEAD‘ helps us achieve just that, and using this method, weundoourcommit(s), but we don’t lose the changes to the code or files we had in those deletedcommit(s).

So to undo the unwanted commit(s) in git using git reset HEAD, this is the syntax that we need to follow -

git reset HEAD~<number-of-commits>

Let us break down and understand the above syntax -

  • git resetsuggests that we are resetting commit(s).
  • HEADis a pointer to the latest commit in our current branch.
  • <number-of-commits>is represented by a number. It represents the number of commits we want to undo.

When we use the above code to undo a commit, our commits in the branch get deleted. But the code inside the files does not get changed. They getunstaged.

This means whatever the changes we had made in the deleted commits stay there safely, no file is lost, and all the codes remain intact.

We may make changes to them according to our needs andadd(stage)them, andcommitthem again.

Let us understand them better with examples.

Example #1

Using the code below, we will undoonelast commit -“5th Commit”from the list of commits in our local git repository.

git reset HEAD~1

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

In the image below, we have used the git log

command to compare the previous(before using the git reset HEAD~3) and current(after using the git reset HEAD~3) commits, and we also view the changes in the file content - File 1.txt accordingly.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (2)

As can be seen, the file content stays intact even after we undo our commit in git, and if any new files were created in the deleted commit, they would be present in the repository too. The only thing is they will get unstaged.

Example #2

We will use this code to undo thethreelast commits -“5th Commit,4th Commit&3rd Commit”from the list of commits in our local git repository.

git reset HEAD~3

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

Let’s compare the previous(before using the git reset HEAD~3) and current(after using the git reset HEAD~3) commits using git log command, and view the changes in the file content - File 1.txt accordingly.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (3)

Usinggit reset HEAD~<number-of-commits>is the recommended way to undo a commit in Git.

The unwanted commits get deleted, but the files and codes do not get affected.

Now we can rectify faults, stage and commit them again as fresh commits.

Pushing theupdated commits to Github(after undoing commits in Git)

There might be instances where after pushing our commits to the remote repository(e.g. Github), we may need to undo commit(s) in Local repository in Git and push them back to that same remote repository again.

Let’s try to understand one such scenario using the image below -

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (4)

In the image above, there are five commits in the remote repository on Github, whereas the local repository has three commits(after undoing two commits).

At this point, if we try pushing our commits from the local repository to the remote repository, we will get an error saying -“Updates were rejected because the tip of your branch is behind“.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (5)

In such cases, we can force update our remote repository using the syntax below -

git push origin +HEAD:<branch-name>

In the syntax above, <branch-name>represents the current branch we are working on in our local repository(after undoing the commits).

If we are on themasterbranch, we need to typemaster.

Currently we are on the branch -“Example_2”, so we will run the following code -

git push origin +HEAD:Example_2

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (6)

As we can see in the image above, after running the above code, we have successfully updated/synced our commits in the remote repository with the commits in our local repository.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (7)

This is how we push theupdated commits to Githubafter we undo commit(s) in local repository in Git.

git reset hard- undo commit(s) in Git -(powerful but destructive)

Sometimes we may come across a situation where we want toundounwantedcommit(s), make that unwanted commit(s)disappearfrom thegit log, along with undoing the changes made to codes and files at that unwanted commit(s).

git reset hard helps us achieve just that, and using this method, weundoourcommit(s), and we also discard the changes to the code or files we had in those deletedcommits.

So to undo the commit(s) in git using ‘git reset --hard‘, this is the syntax that we need to follow -

git reset --hard <commit-id>

Let’s understand the above syntax -

  • git resetsuggests that we are resetting commit(s)
  • hardrepresents that we are resetting the commit in a demanding manner, removing the total changes from our current Head position until that particularcommit-id
  • commit-id is the unique id that represents the commit till where we want our changes to be removed

We need to put the two minuses (-) signs in front of‘hard’as shown in the above syntax.

Let’s understand ‘git reset --hard‘ with an example.

Example-

Let us undo all changes we made in the5th Commit.

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

We will remove all the changes we made to the repository from our current HEAD position until the4th Commit. To do so -

  1. First, we will see the list of commits using thegit logcommand.
  2. Then from the commit named -4th Commit, we will copy itscommit-id.
  3. Lastly, we will paste this commit-id according to the syntax and run this code to undo the changes made till the4th Commit.

Here is the code that we need to run -

git reset --hard de61e821268235f6ca03a061e352bf9b1856e8eb

Refer to the image below to better understand ‘git reset --hard‘.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (8)

As we can see in the image above, our HEAD is now at the4th Commit. We have successfully undone one commit, i.e., the5th Commit, and all the file changes we made inside the5th Commitare now removed.

Usinggit reset --hardto undo a commit in Git is quite powerful. It takes us to any previous timestamp in our code history, but at the same time, it is destructive as well.

If we make a mistake, we will lose all the changes. So we should always be careful when using the ‘git reset --hard‘ command.

NOTE: After using ‘git reset --hard‘, if any error occurs, like -“Updates were rejected because the tip of your branch is behind” while pushing the codes to a remote repository like Github or others, follow these steps.

git revert- undo commit(s) in Git -(code gets reverted on the existing commits)

There can be instances when we have written codes in a commit(s) and later figure out that commit(s) (or the codes written in that commit(s)) is not helpful.

But we want to retain that unwanted commit(s) in the commit history and work back on a commit before that. We can do that usinggit revert.

While using git revert, all the previous commits remain intact. Only anew reverted commitis placed after all the last commits to which the HEAD will now point.

Here is the syntax of using ‘git revert‘ that can be used to undo a commit in git -

git revert <commit-id>

Let’s understand the syntax -

  • git revertindicates that we are reverting our code to a particular previous commit marked by thatcommit-id.
  • commit-id is the unique id that represents the commit till where we want our changes to be reverted (alongwith retaining the codes in unwanted commits)

After we have executed ‘git revert‘ using the above syntax, the window will show us a summary that we have reverted to a particular commit, and we will need to type:q(colon+q) to close that summary UI.

Let us understandgit revertwith an example.

Example-

In this example, we have five different commits.

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

We will add one more line to the File 1.txt file -

L for Last Commit

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (9)

We will add and commit the changes with the name -Last Commit.

Content in the text-file commit-wise
1st CommitA for Apple
2nd CommitA for Apple

B for Ball

3rd CommitA for Apple

B for Ball

C for Cat

4th CommitA for Apple

B for Ball

C for Cat

D for Dog

5th CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

Last CommitA for Apple

B for Ball

C for Cat

D for Dog

E for Elephant

L for Last Commit

But now, we want to go back to the4th Commit. In other words, we want to undo all changes made in theLast Commitand5th Commitand wish to retain these commits, too, in case we need to get back to them later.

So, here is how we use ‘git revert‘ to achieve this -

  • First, we will see the list of commits using thegit logcommand.
  • Then from the commit named -5th Commit, we will copy itscommit-id.
  • We will run this code to revert theLast Commitand5th Commitchanges.

git revert c73d320cd1e7ab976974d48662f98294db3f0f34

  • If there is no conflict, we will get a summary screen of the code we reverted. In that case, we will need to type:q(colon+q) to close that summary UI.
  • Sometimes, we may receive a conflict while using ‘git revert‘. In such a case, we need to -
    • open the local git repository in Visual Studio Code Editor (or any code editor of our choice)
    • go to Source Control (the button on the Left-hand side which has a git symbol on it)
    • select the file which we can see is having conflict
    • resolve the Conflicts
    • stage them.

The image below visualizes the processes we discussed above, alongwith resolving conflicts while using ‘git revert‘.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (10)
  • Next we run thegit logcommand. And now we can see that ourHEADis on the4th Commit, and the changes we made in theLast Commitand5th Commitare reverted.
How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (11)

Alternately, we can also use‘git revert -n‘to undo commit(s) in Git for explicit committing of reverted code.

Down below is the syntax of ‘git revert -n

‘ -

git revert -n <commit-id>

Conclusion

Knowing how to undo commit(s) in Git helps us explore and test new ideas, try exciting concepts.

Being aware of the fact that we can always undo our mistakes and bring the whole code to the previous working state, enhances our coding experience.

We can use three ways to undo commit(s) in Git -

  • Using git reset HEAD
  • Using git reset --hard
  • Using git revert

I hope you found this article helpful.

How To Undo Commit(s) In Git? Git Reset & Git Revert Explained. (12)

You may like to Explore -

3 methods to use Python Switch Case

Indentation in Python – Indent Error Fix

Cheers!

Happy Coding.

About the Author

This article was authored byRawnak.

FAQs

What is the difference between revert and reset and undo in git? ›

For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch. You can also think of git revert as a tool for undoing committed changes, while git reset HEAD is for undoing uncommitted changes.

Does git reset undo commits? ›

git reset is the command responsible for the undo. It will undo your last commit while leaving your working tree (the state of your files on disk) untouched. You'll need to add them again before you can commit them again). Make corrections to working tree files.

How to remove commit after git reset? ›

To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits.

What is the difference between revert commit and undo commit? ›

The git revert command can be considered an 'undo' type command, however, it is not a traditional undo operation. Instead of removing the commit from the project history, it figures out how to invert the changes introduced by the commit and appends a new commit with the resulting inverse content.

What is difference between reset revert and restore? ›

Notice that revert and reset are history altering (making a new commit in former, and moving the tip in the latter), where as restore does not modify history.

What are the three types of git reset? ›

reset --soft : History changed, HEAD changed, Working directory is not changed. reset --mixed : History changed, HEAD changed, Working directory changed with unstaged data. reset --hard : History changed, HEAD changed, Working directory is changed with lost data. It is always safe to go with Git --soft.

Does reverting a commit delete code? ›

Git revert does not delete any commit in this project history. Instead, it inverts the changes implemented in a commit and appends new commits with the opposite effect. This process helps Git remove the unwanted commit from the codebase and retain the history of every commit and the reverted one.

What happens when you undo a commit? ›

Undoing the Last Commit

Reset will rewind your current HEAD branch to the specified revision. In our example above, we'd like to return to the one before the current revision - effectively making our last commit undone. Note the --soft flag: this makes sure that the changes in undone revisions are preserved.

How do I revert multiple commits in git? ›

To revert multiple commits in Git, you can use the `git revert` command along with the commit hashes or range of commits that you want to revert.

How do you undo all commits on a branch? ›

Make sure you are on the branch to which you have been committing. Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.

What is reverse and resetting a commit? ›

The git reset and revert commands are commonly confused, but they apply to distinct use cases. To undo changes associated with a specific commit, developers should use the git revert command. To undo every change that has happened since a given commit occurred, use git reset.

Is revert the same as rollback? ›

I hope that helps. To me, revert means to undo the change prior to committing it. Rollback is to undo a change after committing it.

What is the difference between undo and revert? ›

What's the difference between undoing and reverting? Reverting changes is not the same as undoing an action. Revert returns items to the original state they were downloaded while undo reverses your last action.

What is the difference between git reset and git restore? ›

" reset is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history." " restore is about restoring files in the working tree from either the index or another commit. This command does not update your branch.

Can you restore after a reset? ›

To recover data after factory reset Android, navigate to the "Backup and Restore" section under "Settings." Now, look for the "Restore" option, and choose the backup file you created before resetting your Android phone. Select the file and restore all of your data.

What are the 4 stages in git? ›

Files in a Git project have various stages like Creation, Modification, Refactoring, and Deletion and so on.

How to reset last 3 commits in git? ›

How to Undo Commits with git reset. The git reset command is used to undo changes. Put the corresponding number instead of ~x . For example, if you specify ~3 , the command will affect the three latest commits.

What is the difference between git reset commit and rebase? ›

They are completely different. git-reset works with refs, on your working directory and the index, without touching any commit objects (or other objects). git-rebase on the other hand is used to rewrite previously made commit objects. So if you want to rewrite the history, git-rebase is what you want.

Can we push after commit? ›

When you're ready, click Commit or Commit and Push ( Ctrl+Alt+K ) to push the changes to the remote repository immediately after the commit. You will be able to review the current commit as well as all other commits before they are pushed to the remote.

How to recover reverted changes in git? ›

In this case, you can restore the file using either git checkout or git reflog . You can find the hash-ID of the previous commit from the command: git log . In case you don't have the hash ID, you can use the command git reflog .

What does revert do? ›

While revert means to return to something earlier or to go back, it's often used wrongly in combination. If you're buying the older version of the game, you might say you're "reverting back," which is like saying "go back back."

How to remove 3 commits in git? ›

If the commits you want to remove are placed at the top of your commit history, use the git reset --hard command with the HEAD object and the number of commits you want to remove. This command will remove the latest commit. This command will remove the latest three commits.

Can I revert two commits? ›

Reverting changes means undoing one or more commits that have already been pushed to the repository. Git revert is a powerful command that can be used to undo multiple commits at once. It creates a new commit that undoes the changes introduced by one or more previous commits.

How do I undo a commit and pull? ›

There is no command to explicitly undo the git pull command. The alternative is to use git reset, which reverts a repository back to a previous commit. We're working on a project called ck-git. A collaborator has just pushed a commit to the remote version of the project that is stored on GitHub.

What are examples of revert back? ›

: to go back or return to (an earlier state, condition, situation, etc.) She has reverted (back) to her old habits. (chiefly Brit) After this one atypical comedy, will he revert to type [=will he do what he usually does] in his next film?

What are the advantages of rollback? ›

Advantages and Disadvantages of Roll Backs

Traders can take advantage of rolling back on their options contracts in order to reduce market risk, which can put the investor's entire investment in jeopardy. By cutting back on the risks, roll backs also allow traders to cut down on losses and lock in their profits.

Is revert the same as undo? ›

It is an “undo” command, but technically it is much more than that. Git revert does not delete any commit in this project history. Instead, it inverts the changes implemented in a commit and appends new commits with the opposite effect.

What does reset mean in git? ›

Summary. To review, git reset is a powerful command that is used to undo local changes to the state of a Git repo. Git reset operates on "The Three Trees of Git". These trees are the Commit History ( HEAD ), the Staging Index, and the Working Directory.

What is the difference between git reset and rebase? ›

They are completely different. git-reset works with refs, on your working directory and the index, without touching any commit objects (or other objects). git-rebase on the other hand is used to rewrite previously made commit objects. So if you want to rewrite the history, git-rebase is what you want.

What does reverting a commit do? ›

The "revert" command helps you undo an existing commit.

It's important to understand that it does not delete any data in this process: instead, Git will create new changes with the opposite effect - and thereby undo the specified old commit.

Does revert mean get back? ›

While revert means to return to something earlier or to go back, it's often used wrongly in combination. If you're buying the older version of the game, you might say you're "reverting back," which is like saying "go back back."

How do I undo recent commits? ›

Undoing Your Last Commit (That Has Not Been Pushed)
  1. In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo.
  2. Run this command: git reset --soft HEAD~ ...
  3. Your latest commit will now be undone.

How do you reverse a commit? ›

Steps to revert a Git commit
  1. Locate the ID of the commit to revert with the git log or reflog command.
  2. Issue the git revert command and provide the commit ID of interest.
  3. Supply a meaningful Git commit message to describe why the revert was needed.
Dec 1, 2021

Is it possible to revert a merge? ›

You can use the Git reset command to undo a merge. Firstly, you need to check for the commit hash (or id) so you can use it to go back to the previous commit. To check for the hash, run git log or git reflog . git reflog is a better option because things are more readable with it.

What is difference between pull and fetch in git? ›

The git fetch command first fetches the changes from the remote repository and then stored the changes in a separate branch in our local repository. On the other hand, the git pull command pulls all the changes from the remote repository to our corresponding branch of the local repository.

Does git reset delete files? ›

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded. Any untracked files or directories in the way of writing any tracked files are simply deleted.

References

Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated: 12/08/2023

Views: 6210

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.