26329

I accidentally committed the wrong files to Git, but didn't push the commit to the server yet.

How do I undo those commits from the local repository?

15
  • 720
    You know what git needs? git undo, that's it. Then the reputation git has for handling mistakes made by us mere mortals disappears. Implement by pushing the current state on a git stack before executing any git command. It would affect performance, so it would be best to add a config flag as to whether to enable it.
    – Yimin Rong
    Mar 20, 2018 at 1:45
  • 61
    @YiminRong That can be done with Git's alias feature: git-scm.com/book/en/v2/Git-Basics-Git-Aliases
    – Edric
    Oct 5, 2018 at 14:50
  • 143
    For VsCode users , just type ctrl +shift +G and then click on three dot ,ie , more options and then click on undo Last Commit
    – ashad
    Apr 8, 2019 at 12:15
  • 34
    @YiminRong Undo what exactly? There are dozens of very different functional cases where "undoing" means something completely different. I'd bet adding a new fancy "magic wand" would only confuse things more. Mar 24, 2020 at 14:27
  • 54
    @YiminRong Not buying it. People would still fumble and undo things not to be undone. But more importantly, git reflog is already close to what you describe, but gives the user more control on what's to be (un)done. But please, no, "undo" does not work the same everywhere, and people would expect many different things for the feature to achieve. Undo last commit? Undo last action? If last action was a push, undo how exactly, (reset and push) or (revert and push)? Mar 25, 2020 at 13:23

106 Answers 106

145

To reset to the previous revision, permanently deleting all uncommitted changes:

git reset --hard HEAD~1
6
  • 24
    Maybe you could at a note/warning that his command will throw away the commit and the changes in the working directory without asking any further. Nov 24, 2014 at 22:35
  • 6
    If you happen to do this by accident, not all is lost, though. See stackoverflow.com/questions/10099258/…, stackoverflow.com/questions/15479501/… and stackoverflow.com/questions/7374069/undo-git-reset-hard/7376959. Nov 24, 2014 at 22:40
  • 13
    Use --soft to keep your changes as uncommitted changes, --hard to nuke the commit completely and revert back by one. Remember to do such operations only on changes, that are not pushed yet. Mar 9, 2015 at 9:11
  • @Zaz: You are right; maybe I should have clarified that. Only files/changes that have been either added to index (/staged) or have been committed can possibly be recovered. Uncommitted, unstaged changes are, as you said, completely thrown away by git reset --hard. Sep 13, 2016 at 21:17
  • 1
    As a sidenote: Everytime a file is staged, git stores its contents in its object database. The stored contents are only removed when garbage collection is executed. It is therefore possible to recover the last staged version of a file that was not currently staged when git reset --hard was executed (see the posts linked above for more information). Sep 13, 2016 at 21:22
136

Use SourceTree (graphical tool for Git) to see your commits and tree. You can manually reset it directly by right clicking it.

104

A simple step-by-step guide is as follows:

  • Destroy a commit and throw away any uncommitted changes

    git reset --hard HEAD~1
    
  • Undo the commit, but keep your changes

    git reset HEAD~1
    
  • Keep your files, and stage all changes back automatically

    git reset --soft HEAD~1
    
  • Resurrect a commit you destroyed

    git reflog # To find the sh
    
2
  • 2
    What do you mean by "To find the sh"? Do you mean "To find the SHA-1 hash value"? Or something else? Mar 30, 2023 at 11:40
  • Yes, sh is a thing too...
    – mirekphd
    Aug 10, 2023 at 16:34
100

Think we have code.txt file. We make some changes on it and commit. We can undo this commit in three ways, but first you should know what is the staged file... An staged file is a file that ready to commit and if you run git status this file will be shown with green color and if this is not staged for commit will be shown with red color:

enter image description here

It means if you commit your change, your changes on this file is not saved. You can add this file in your stage with git add code.txt and then commit your change:

enter image description here

Undo last commit:

  1. Now if we want to just undo commit without any other changes, we can use

    git reset --soft HEAD^

    enter image description here

  2. If we want to undo commit and its changes (THIS IS DANGEROUS, because your change will lost), we can use

    git reset --hard HEAD^

    enter image description here

  3. And if we want to undo commit and remove changes from stage, we can use

    git reset --mixed HEAD^ or in a short form git reset HEAD^

    enter image description here

0
89

Usually, you want to undo a commit because you made a mistake and you want to fix it - essentially what the OP did when he asked the question. Really, you actually want to redo a commit.

Most of the answers here focus on the command line. While the command line is the best way to use Git when you're comfortable with it, its probably a bit alien to those coming from other version control systems to Git.

Here's how to do it using a GUI. If you have Git installed, you already have everything you need to follow these instructions.

NOTE: I will assume here that you realised the commit was wrong before you pushed it. If you don't know what pushing means, then you probably haven't pushed. Carry on with the instructions. If you have pushed the faulty commit, the least risky way is just to follow up the faulty commit with a new commit that fixes things, the way you would do it in a version control system that does not allow you to rewrite history.

That said, here's how to fix your most recent fault commit using a GUI:

  1. Navigate to your repository on the command line and start the GUI with git gui
  2. Choose "Amend last commit". You will see your last commit message, the files you staged and the files you didn't.
  3. Now change things to how you want them to look and click Commit.
84

If you want to revert the last commit but still want to keep the changes locally that were made in the commit, use this command:

git reset HEAD~1 --mixed
2
  • 13
    The right answer without the git tutorial.
    – Ringo
    Nov 15, 2021 at 0:31
  • 2
    Simple and worked for me. I reset my password, logged in, hunted for this answer in the list since it was not in the same order, and voted you up. Nov 20, 2021 at 20:31
81

You can use:

git reset HEAD@{1}

This command will delete your wrong commit without a Git log.

0
76

Undo the Last Commit

There are tons of situations where you really want to undo that last commit into your code. E.g. because you'd like to restructure it extensively - or even discard it altogether!

In these cases, the "reset" command is your best friend:

$ git reset --soft HEAD~1

The above command (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. After running the command, you'll find the changes as uncommitted local modifications in your working copy.

If you don't want to keep these changes, simply use the --hard flag. Be sure to only do this when you're sure you don't need these changes any more.

$ git reset --hard HEAD~1

Enter image description here

2
  • "Working copy"? Is this a Git concept? Isn't it an SVN concept? Jan 28, 2018 at 21:36
  • @PeterMortensen yes working copy, its a git concept though
    – Mohit
    May 4, 2018 at 19:46
74

Just undo the last commit:

git reset --soft HEAD~

Or undo the time before last time commit:

git reset --soft HEAD~2

Or undo any previous commit:

git reset --soft <commitID>

(you can get the commitID using git reflog)

When you undo a previous commit, remember to clean the workplace with

git clean

More details can be found in the docs: git-reset

68

Before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

67

In my case I committed and pushed to the wrong branch, so what I wanted was to have all my changes back so I can commit them to a new correct branch, so I did this:

On the same branch that you committed and pushed, if you type "git status" you won't see anything new because you committed and pushed, now type:

    git reset --soft HEAD~1

This will get all your changes(files) back in the stage area, now to get them back in the working directory(unstage) you just type:

git reset FILE

Where "File" is the file that you want to commit again. Now, this FILE should be in the working directory(unstaged) with all the changes that you did. Now you can change to whatever branch that you want and commit the changes in that branch. Of course, the initial branch that you committed is still there with all changes, but in my case that was ok, if it is not for you-you can look for ways to revert that commit in that branch.

65

Undo the last commit:

git reset --soft HEAD^ or git reset --soft HEAD~

This will undo the last commit.

Here --soft means reset into staging.

HEAD~ or HEAD^ means to move to commit before HEAD.

Replace the last commit to new commit:

git commit --amend -m "message"

It will replace the last commit with the new commit.

0
62

If you are working with SourceTree, this will help you.

Right click on the commit then select "Reset (current branch)/master to this commit" and last select "Soft" reset.

Enter image description here

60

To undo your local commit you use git reset <commit>. Also that tutorial is very helpful to show you how it works.

Alternatively, you can use git revert <commit>: reverting should be used when you want to add another commit that rolls back the changes (but keeps them in the project history).

2
  • Be extra careful when reverting merge commits. You may lose your commits. Read about what Linus says about that: kernel.org/pub/software/scm/git/docs/howto/… Dec 15, 2016 at 16:25
  • Note that for git reset <commit>, use the commit sha for the PREVIOUS commit that you want to reset to, not the commit that you want to unstage.
    – Rich G
    Jul 7, 2022 at 15:25
58

Suppose you made a wrong commit locally and pushed it to a remote repository. You can undo the mess with these two commands:

First, we need to correct our local repository by going back to the commit that we desire:

git reset --hard <previous good commit id where you want the local repository  to go>

Now we forcefully push this good commit on the remote repository by using this command:

git push --force-with-lease

The 'with-lease' version of the force option it will prevent accidental deletion of new commits you do not know about (i.e. coming from another source since your last pull).

1
  • 1
    this worked for me the best, since I had already pushed the bad commit up to github
    – AeroHil
    May 6, 2019 at 20:36
53

VISUAL STUDIO USERS (2015, etc.)

If you cannot synchronise in Visual Studio as you are not allowed to push to a branch like "development" then as much as I tried, in Visual Studio NEITHER the REVERT NOR the RESET (hard or soft) would work.

Per the answer with TONS OF VOTES:

Use this at the command prompt of root of your project to nuke anything that will attempt to get pushed:

git reset --hard HEAD~1

Backup or zip your files just in case you don't wish to lose any work, etc...

53

Everybody comments in such a complicated manner.

If you want to remove the last commit from your branch, the simplest way to do it is:

git reset --hard HEAD~1

Now to actually push that change to get rid of your last commit, you have to

git push --force

And that's it. This will remove your last commit.

2
  • 6
    But keep in mind that --hard will completely discard all the changes that were made in the last commit as well as the content of the index.
    – CloudJR
    Mar 14, 2020 at 11:58
  • Yes, in the case we need to just fix the commit, we shoud not use --hard`, but leave it with the default --soft` so we can remove and add stuff before the ``git push -f`
    – Maf
    Mar 11, 2021 at 16:29
52

A Typical Git Cycle

In speaking of Git-related commands in the previous answers, I would like to share my typical Git cycles with all readers which may helpful. Here is how I work with Git,

  1. Cloning the first time from the remote server

    git clone $project

  2. Pulling from remote (when I don't have a pending local commit to push)

    git pull

  3. Adding a new local file1 into $to_be_committed_list (just imagine $to_be_committed_list means staged area)

    git add $file1

  4. Removing mistakenly added file2 from $to_be_committed_list (assume that file2 is added like step 3, which I didn't want)

    git reset $file2

  5. Committing file1 which is in $to_be_committed_list

    git commit -m "commit message description"

  6. Syncing local commit with remote repository before pushing

    git pull --rebase

  7. Resolving when conflict occurs prerequisite configure mergetool

    git mergetool #resolve merging here, also can manually merge

  8. Adding conflict-resolved files, let's say file1:

    git add $file1

  9. Continuing my previous rebase command

    git rebase --continue

  10. Pushing ready and already synced last local commit

    git push origin head:refs/for/$branch # branch = master, dev, etc.

1
  • What if I am working on a fork, so basically I have 2 remotes actual repo e.g. incubator-mxnet and my forked repo ChaiBapchya/incubator-mxnet So in such a case, how can I solve merge conflicts from local to my forked repo branch Oct 30, 2018 at 19:18
49

In these cases, the "reset" command is your best friend:

git reset --soft HEAD~1

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. After running the command, you'll find the changes as uncommitted local modifications in your working copy.

If you don't want to keep these changes, simply use the --hard flag. Be sure to only do this when you're sure you don't need these changes anymore.

git reset --hard HEAD~1
47

In order to get rid of (all the changes in) last commit, last 2 commits and last n commits:

git reset --hard HEAD~1
git reset --hard HEAD~2
...
git reset --hard HEAD~n

And, to get rid of anything after a specific commit:

git reset --hard <commit sha>

e.g.,

git reset --hard 0d12345

Be careful with the hard option: it deletes the local changes in your repo as well and reverts to the previous mentioned commit. You should only run this if you are sure you messed up in your last commit(s) and would like to go back in time.

As a side-note, about 7 letters of the commit hash is enough, but in bigger projects, you may need up to 12 letters for it to be unique. You can also use the entire commit SHA if you prefer.

The above commands work in GitHub for Windows as well.

46

Remove a wrong commit that is already pushed to Github

git push origin +(previous good commit id):(branch name)

Please specify the last good commit id you would like to reset back in Github.

For example. If latest commit id is wrong then specify the previous commit id in above git command with the branch name.

You can get previous commit id using git log

42

You need to do the easy and fast

    git commit --amend

if it's a private branch or

    git commit -m 'Replace .class files with .java files'

if it's a shared or public branch.

42

I got the commit ID from bitbucket and then did:

git checkout commitID .

Example:

git checkout 7991072 .

And it reverted it back up to that working copy of that commit.

1
  • Note: checking out '5456cea9'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at 5456cea... Need to delete Exclusions.xslt from Documentation folder. - Delete What should i do after this
    – cSharma
    May 22, 2019 at 14:02
36

Do as the following steps.

Step 1

Hit git log

From the list of log, find the last commit hash code and then enter:

Step 2

git reset <hash code>
1
  • After this, how can I fix the wrong commit to exclude wrong files?
    – Maf
    Mar 11, 2021 at 16:23
33

Use this command

git checkout -b old-state 0d1d7fc32
33

In order to remove some files from a Git commit, use the “git reset” command with the “–soft” option and specify the commit before HEAD.

$ git reset --soft HEAD~1

When running this command, you will be presented with the files from the most recent commit (HEAD) and you will be able to commit them.

Now that your files are in the staging area, you can remove them (or unstage them) using the “git reset” command again.

$ git reset HEAD <file>

Note: this time, you are resetting from HEAD as you simply want to exclude files from your staging area

If you are simply not interested in this file any more, you can use the “git rm” command in order to delete the file from the index (also called the staging area).

$ git rm --cached <file>

When you are done with the modifications, you can simply commit your changes again with the “–amend” option.

$ git commit --amend

To verify that the files were correctly removed from the repository, you can run the “git ls-files” command and check that the file does not appear in the file (if it was a new one of course)

$ git ls-files

 <file1>
 <file2>

Remove a File From a Commit using Git Restore

Since Git 2.23, there is a new way to remove files from commit, but you will have to make sure that you are using a Git version greater or equal than 2.23.

$ git --version

Git version 2.24.1

Note: Git 2.23 was released in August 2019 and you may not have this version already available on your computer.

To install newer versions of Git, you can check this tutorial. To remove files from commits, use the “git restore” command, specify the source using the “–source” option and the file to be removed from the repository.

For example, in order to remove the file named “myfile” from the HEAD, you would write the following command

$ git restore --source=HEAD^ --staged  -- <file>

As an example, let’s pretend that you edited a file in your most recent commit on your “master” branch.

The file is correctly committed but you want to remove it from your Git repository.

To remove your file from the Git repository, you want first to restore it.

$ git restore --source=HEAD^ --staged  -- newfile

$ git status

On branch 'master'

Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)

Changes to be committed:

 (use "git restore --staged <file>..." to unstage)
    modified:   newfile

Changes not staged for commit:

 (use "git add <file>..." to update what will be committed)
 (use "git restore <file>..." to discard changes in working directory)
      modified:   newfile

As you can see, your file is back to the staging area.

From there, you have two choices, you can choose to edit your file in order to re-commit it again, or to simply delete it from your Git repository.

Remove a File from a Git Repository

In this section, we are going to describe the steps in order to remove the file from your Git repository.

First, you need to unstage your file as you won’t be able to remove it if it is staged.

To unstage a file, use the “git reset” command and specify the HEAD as source.

$ git reset HEAD newfile

When your file is correctly unstaged, use the “git rm” command with the “–cached” option in order to remove this file from the Git index (this won’t delete the file on disk)

$ git rm --cached newfile

rm 'newfile'

Now if you check the repository status, you will be able to see that Git staged a deletion commit.

$ git status

On branch 'master'

Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)

Changes to be committed:

 (use "git restore --staged <file>..." to unstage)
    deleted:    newfile

Now that your file is staged, simply use the “git commit” with the “–amend” option in order to amend the most recent commit from your repository.

`$ git commit --amend

 [master 90f8bb1] Commit from HEAD
  Date: Fri Dec 20 03:29:50 2019 -0500
  1 file changed, 2 deletions(-)
  delete mode 100644 newfile

`As you can see, this won’t create a new commit but it will essentially modify the most recent commit in order to include your changes.

Remove a Specific File from a Git Commit

In some cases, you don’t want all the files to be staged again: you only one to modify one very specific file of your repository.

In order to remove a specific file from a Git commit, use the “git reset” command with the “–soft” option, specify the commit before HEAD and the file that you want to remove.

$ git reset HEAD^ -- <file>

When you are done with the modifications, your file will be back in the staging area.

First, you can choose to remove the file from the staging area by using the “git reset” command and specify that you want to reset from the HEAD.

$ git reset HEAD <file>

Note: it does not mean that you will lose the changes on this file, just that the file will be removed from the staging area.

If you want to completely remove the file from the index, you will have to use the “git rm” command with the “–cached” option.

$ git reset HEAD <file>

In order to make sure that your file was correctly removed from the staging area, use the “git ls-files” command to list files that belong to the index.

$ git ls-files

When you are completely done with your modifications, you can amend the commit you removed the files from by using the “git commit” command with the “–amend” option.

$ git commit --amend
1
  • What's the difference between using git rm file` and git checkout file`?
    – Maf
    Mar 11, 2021 at 16:37
32

Use this command:

git checkout -b old-state number_commit
32
git reset --soft HEAD~1

Reset will rewind your current HEAD branch to the specified revision.

Note the --soft flag: this makes sure that the changes in undone revisions are preserved. After running the command, you'll find the changes as uncommitted local modifications in your working copy.

If you don't want to keep these changes, simply use the --hard flag. Be sure to only do this when you're sure you don't need these changes anymore.

 git reset --hard HEAD~1

Undoing Multiple Commits

git reset --hard 0ad5a7a6

Keep in mind, however, that using the reset command undoes all commits that came after the one you returned to:

Enter image description here

32

Undoing a series of local commits

OP: How do I undo the most recent local commits in Git? I accidentally committed the wrong files [as part of several commits].

Start case

There are several ways to "undo" as series of commits, depending on the outcome you're after. Considering the start case below, reset, rebase and filter-branch can all be used to rewrite your history.

Star-case

How can C1 and C2 be undone to remove the tmp.log file from each commit?

In the examples below, absolute commit references are used, but it works the same way if you're more used to relative references (i.e. HEAD~2 or HEAD@{n}).

Alternative 1: reset

$ git reset --soft t56pi

using-reset

With reset, a branch can be reset to a previous state, and any compounded changes be reverted to the Staging Area, from where any unwanted changes can then be discarded.

Note: As reset clusters all previous changes into the Staging Area, individual commit meta-data is lost. If this is not OK with you, chances are you're probably better off with rebase or filter-branch instead.

Alternative 2: rebase

$ git rebase --interactive t56pi

using-rebase

Using an interactive rebase each offending commit in the branch can be rewritten, allowing you to modify and discard unwanted changes. In the infographic above, the source tree on the right illustrates the state post rebase.

Step-by-step

  1. Select from which commit the rebase should be based (e.g. t56pi)
  2. Select which commits you'd like to change by replacing pick with edit. Save and close.
  3. Git will now stop on each selected commit allowing you to reset HEAD, remove the unwanted files, and create brand new commits.

Note: With rebase much of the commit meta data is kept, in contrast to the reset alternative above. This is most likely a preferred option, if you want to keep much of your history but only remove the unwanted files.

Alternative 3: filter-branch

$ git filter-branch --tree-filter 'rm -r ./tmp.log' t56pi..HEAD

Above command would filter out the file ./tmp.log from all commits in the desired range t56pi..HEAD (assuming our initial start case from above). See below illustration for clarity.

using-filter-branch

Similar to rebase, filter-branch can be used to wipe unwanted files from a subsection of a branch. Instead of manually editing each commit through the rebase process, filter-branch can automatically preformed the desired action on each commit.

Note: Just like rebase, filter-branch would preserve the rest of the commit meta-data, by only discarding the desired file. Notice how C1 and C2 have been rewritten, and the log-file discarded from each commit.

Conclusion

Just like anything related to software development, there are multiple ways to achieve the same (or similar) outcome for a give problem. You just need to pick the one most suitable for your particular case.

Finally - a friendly advice

Do note that all three alternatives above rewrites the history completely. Unless you know exactly what you're doing and have good communication within your team - only rewrite commits that have not yet been published remotely!

Source: All examples above are borrowed from this blog.

32

To undo the most recent local commits in Git, you have a couple of options depending on what you want to do:

Soft Reset: If you want to keep the changes from the commits but just undo the commit itself, you can use a soft reset. This will move the HEAD pointer to a previous commit without altering the working directory or staging area.

git reset --soft HEAD~1

This command will remove the most recent commit from the branch but keep the changes from that commit in the staging area. You can then make further modifications or commit again.

Mixed Reset: If you want to undo the commit and also unstage the changes (but keep them in your working directory), you can use a mixed reset.

bash

git reset --hard HEAD~1

Caution: Using git reset --hard will remove all changes made in the most recent commit irreversibly. Be sure that you want to discard these changes before using this command.

Remember to replace HEAD~1 with the number of commits you want to undo if it's more than one. Also, be cautious when using reset commands, especially --hard, as it can discard changes irreversibly.

Not the answer you're looking for? Browse other questions tagged or ask your own question.