Home >Technology peripherals >It Industry >5 Ways to Undo Mistakes with Git

5 Ways to Undo Mistakes with Git

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-10 12:19:08759browse

5 Ways to Undo Mistakes with Git

Software development, no matter how experienced it is, it is inevitable to make mistakes. But the difference between a good programmer and an ordinary programmer is that they know how to revoke error!

If you use Git as your version control system, you already have a powerful set of "undo tools". This article will show you five powerful ways to undo errors with Git!

Key Points

  • Git allows users to undo errors in code by discarding unwanted local changes. This can be done using the git restore command, which resets the file to its last committed state. For more granular control, you can use the -p flag to discard changes at the patch level.
  • The
  • git log command can be used to restore a specific file to a specific version. The user can identify the "error commit" of a corrupt file and then use the git checkout command to restore the file to a version before the wrong commit.
  • Git's Reflog tool can be used to restore lost versions or deleted branches. Reflog Records movement of all HEAD pointers in the local repository, allowing the user to return to the previous state and restore lost data.
  • Users can use the git cherry-pick command to move the commit to a different branch. If the commit is to the wrong branch, the user can check out the correct branch, move the commit past, and then use git reset to delete the unwanted commit from the original branch.

Discard some local changes

The encoding process is usually confusing. Sometimes it feels like two steps forward and one step back. In other words: some of the code you write is great…but some are not. This is where Git can help you: It allows you to keep the good parts and discard changes you no longer need.

Let's look at a sample scenario that contains some "local" changes (i.e. changes that have not been submitted yet).

5 Ways to Undo Mistakes with Git

Note: For a better overview and clearer visualization, I used the Tower Git desktop client in some screenshots. You don't need a Tower to learn this tutorial.

Let's solve the problem in general.css first. The changes we made were going completely in the wrong direction. Let's undo all changes and recreate the last commit status of the file:

<code class="language-bash">$ git restore css/general.css</code>

Please note that, or, I can use the git checkout command to achieve the same result. But because git checkout has many different uses and meanings, I prefer to use the slightly updated git restore command (it only focuses on these types of tasks).

Our second question in index.html is a bit tricky. Some of the changes we made in this file are actually good, and only a portion needs to be undocumented.

5 Ways to Undo Mistakes with Git

Same, the git restore command will solve the problem - but this time you need to use the -p flag, because we are going to go deep into the "patch" level:

<code class="language-bash">$ git restore css/general.css</code>

Git will then guide you and ask you - for every change in in that file - if you want to discard it.

5 Ways to Undo Mistakes with Git

You will notice that I typed "n" for the first block change (to keep it) and "y" for the second block change (to discard it). Once the process is completed, you will see that only the first piece of valuable changes remained—as we wanted!

Reset a specific file to its previous state

Sometimes, you may want to restore the

specific file to the specific version. For example, you know worked fine at some point in the past, but not now. At this point you want to go back time, but only for this specific file, not the entire project! index.html

We first need to find out which exact version we want to restore. Using the correct parameter set, you can have the

command display the history of your individual file: git log

<code class="language-bash">$ git restore -p index.html</code>

5 Ways to Undo Mistakes with Git

This will only show the

changed commits, which is very useful for finding the "bad Apple" version that causes the problem to appear. index.html

If you need more information and want to view the

content of these commits, you can have Git use the flag to display the actual changes in these commits: -p

<code class="language-bash">$ git log -- index.html</code>
Once we find the wrong commit that caused our cute little file to be corrupted, we can proceed to fix the error. We will do this by restoring the

version of the file before the commit! This is important: instead of resuming the file in the incorrect commit, we restore the last good state-the one before the commit!

<code class="language-bash">$ git log -p -- index.html</code>
Attending

to the hash value of the wrong commit will instruct Git to do the following: Go to a version of the referenced commit ~1 before .

After executing this command, you will find that

has been modified in your local working copy: Git restored the last good version of the file for us! index.html

Recover lost versions using Reflog

Another powerful undo tool in Git first aid kit is "Reflog". You can think of it as a log where Git records all the HEAD pointer movements that occur in the local repository—such as commit, checkout, merge and rebase, cherry-pick, and reset. All the more important operations will be well recorded here!

Of course, such logs are perfect for situations where things are not going well. So let's create a small disaster first - then we can fix it with Reflog.

Suppose you are sure that your last few commits are not good: you want to get rid of them, so you used git reset to return to the previous version. As a result, the "error" commit disappeared from your commit history - as you want it to.

5 Ways to Undo Mistakes with Git

But as life sometimes does, you notice that it's a bad idea: ultimately, these submissions aren't that bad! But the bad news is that you just deleted them from your repository's commit history! ?

5 Ways to Undo Mistakes with Git

This is a classic case of Git's Reflog tool! Let's see how it saves you:

<code class="language-bash">$ git restore css/general.css</code>

5 Ways to Undo Mistakes with Git

Let's break it down one by one:

  • First of all, Reflog is very easy to open: a simple git reflog is enough.
  • Secondly, you will notice that the recorded status is sorted in chronological order, with the latest status at the top.
  • If you look closely, you will find that the top (that is, the latest) project is a "reset" operation. This is exactly what we did 20 seconds ago. Obviously, this log is valid?
  • If we want to undo our unintentional "reset" now, we can simply return to our previous state - this is also well documented here! We can simply copy the commit hash of that previous state to the clipboard and start from it.

To restore this previous state, we can use git reset again, or simply create a new branch:

<code class="language-bash">$ git restore -p index.html</code>

5 Ways to Undo Mistakes with Git

As we can happily verify, our new branch contains commits we think are lost through an unexpected git reset failure!

Recover deleted branches

Reflog can also come in handy in other situations. For example, when you accidentally delete a branch that you shouldn't really be deleting. Let's take a look at our example scenario:

<code class="language-bash">$ git log -- index.html</code>

Let's assume our client/team leader/project manager tells us that the beautiful analytics we've been developing are no longer needed. We are well organized and of course we will delete the corresponding feature/analytics branch!

Above you can see that in our example scenario, we currently checked out the branch: feature/analytics is our current HEAD branch. In order to be able to delete it, we must first switch to another branch:

<code class="language-bash">$ git restore css/general.css</code>

Git tells us we're about to do something very serious: Since feature/analytics contains unique commits that don't exist elsewhere, deleting it will destroy some (probably valuable) data. OK... Since this feature is no longer needed, we can continue:

<code class="language-bash">$ git restore -p index.html</code>

You may have expected what will happen next: Our client/team leader/project manager happily tells us that the feature is back! ? They want to keep going after all! ?

Similarly, we are facing a bad situation where we may have lost valuable data! So let's see if Reflog can save us again:

<code class="language-bash">$ git log -- index.html</code>

5 Ways to Undo Mistakes with Git

If you look closely, the good news will be obvious. Before we can (disastrously) be able to delete our branch, we have to do git checkout to switch to another branch (because Git doesn't allow you to delete the current branch). Of course, this checkout is also recorded in Reflog. To restore the branch we have deleted, we can now simply use the state of before as the starting point for the new branch:

<code class="language-bash">$ git log -p -- index.html</code>

Look: Our branch has come back to life! ???

If you happen to be using a desktop GUI like Tower, undoing such errors is usually as easy as pressing CMD Z.

5 Ways to Undo Mistakes with Git

Move commits to different branches

Finally, let's look at a classic case of the "Oh, no!" department: Submit on the wrong branch.

Today, many teams have formulated a rule that prohibits direct submission to long-term branches such as "main", "master" or "develop". Typically, new commits should only reach these branches by merging/rebase. However, we sometimes forget and submit directly...

Let's take the following scenario as an example.

5 Ways to Undo Mistakes with Git

We should have submitted on feature/newsletter but inadvertently triggered the commit on the master branch. Let's take a look at the solution step by step.

First of all, we have to make sure this time we are on the right branch, so we are checking out feature/newsletter:

<code class="language-bash">$ git checkout <bad-commit-hash>~1 -- index.html</bad-commit-hash></code>

Now we can move the commit safely by using the cherry-pick command:

<code class="language-bash">$ git reflog</code>

We can check feature/newsletter and will see that the commit is now also present here.

5 Ways to Undo Mistakes with Git

So far, everything went well. But cherry-pick does not delete the commit from the master branch (it forever should not be there). So we have to clean up our mess there too:

<code class="language-bash">$ git restore css/general.css</code>

We switch back to master and use git reset to delete (here) unwanted commits from the history.

End, everything returned to normal-so you can start your happy dance now! ???

Unlock error is a superpower

I said it before, and unfortunately we all know it is true: we cannot avoid errors! No matter how good we are programmers, we will mess it up every now and then. So the question is not whether we make mistakes, but how do we handle them effectively and solve problems? If you want to learn more about Git Undo Tools, I highly recommend the "Git First Aid Kit". This is a (free) short video collection that shows you how to clean up and undo errors in Git.

I wish you a smooth development, a courage to try, and of course you must be good at repairing!

FAQs about using Git to undo errors (FAQ)

What is the difference between

and

?

git resetgit revert and

are two commands that help you undo the changes in your Git repository, but they work differently.

Move your HEAD pointer to a specific commit. This means it actually "forgot" all commits you have after the reset to the commit. This is a destructive operation and should be used with caution. On the other hand, git reset creates a new commit to undo the changes made in a specific commit. This is a safe operation because it does not change existing history. git revert git resetHow to undo the git revert operation?

If you have already used git add to save the changes and want to undo this, you can use the

command. For example, if you want to unstack a specific file, you can use the command

. If you want to unstack all changes, you can use git add without specifying the file. git reset git reset <file></file>Can I undo git reset?

Yes, you can undo using the git commit or

command.

Move your HEAD pointer back to the commit you want to undo, effectively erasing unwanted commits. On the other hand, git reset will create a new commit to undo the changes made in the unwanted commit. git revert git commitHow to undo changes in a specific file? git reset git revert If you have made changes to a specific file and want to undo these changes, you can use the

command. For example,

will discard changes in the local working directory of the specified file.

git stash What is it?

git stash is a command that allows you to temporarily save changes that you do not want to submit immediately. This is useful if you need to switch to a different branch but don't want to commit the current change. You can apply the temporary changes later using git stash apply.

How to view my Git history?

You can use the git log command to view your Git history. This will show you a list of all commits in the repository, as well as their commit messages.

Can I undo git push?

Yes, you can undo git push, but this is a little more complicated than undoing local changes. You need to use the -f command with the --force or git push options to overwrite the remote repository with your local repository. Be careful with this command, as it may cause problems for other people who are dealing with the same repository.

How to undo multiple commits?

If you want to undo multiple commits, you can use the git reset command and the HEAD~<number></number> syntax. For example, git reset HEAD~3 moves your HEAD pointer back before three commits.

What is the difference between soft reset and hard reset?

Soft reset moves your HEAD pointer to a specific commit, but does not change your working directory and staging area. This means you will still see changes from "Forgotten" commits as uncommitted changes. On the other hand, a hard reset will discard all changes in the working directory and staging area, effectively restoring your repository to the state at the time of the specified commit.

Can I resume the commit after a hard reset?

Yes, commits can be resumed after a hard reset, but it's not easy. Git keeps logs for all ref updates (such as moving HEAD pointers) in the reflog. You can use the git reflog command to find the commit you want to recover, and then use git branch to create a new branch at that commit.

The above is the detailed content of 5 Ways to Undo Mistakes with Git. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn