25854

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?

Mehdi Charife
  • 722
  • 1
  • 7
  • 22
Hamza Yerlikaya
  • 49,047
  • 44
  • 147
  • 241
  • 2
    See this guide for Git commits undo on Local, Public and Git Branch [How to undo Git Commits like pro](http://justcode.me/git/undo-git-commits/) – Luzan Baral Feb 27 '17 at 03:53
  • 663
    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 '18 at 01:45
  • 57
    @YiminRong That can be done with Git's `alias` feature: https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases – Edric Oct 05 '18 at 14:50
  • 124
    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 08 '19 at 12:15
  • 26
    @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. – Romain Valeri Mar 24 '20 at 14:27
  • 49
    @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)? – Romain Valeri Mar 25 '20 at 13:23
  • 10
    To do something simple in git either do Impossibly Hard Task A or Impossibly Hard Task B. Then mess it up slightly and try and revert by doing Impossibly Hard Task C or Impossibly Hard Task D. – Snowcrash Oct 19 '20 at 14:27
  • 4
    Git is a framework to deal with versioning of many files and allow collaborative work. It requires absolute control about what you are doing to accomplish those goals. It is great _precisely_ because it tries to leave all the unnecessary "magic" out. Something like `git undo` is generally a bad idea, but is ridiculously easy to implement if you really want to. But then, be aware, you are responsible for it. I find really amazing how people would so promptly give up control to not have to learn stuff. Git is _easy_ you just have to learn the concepts. – Victor Schröder Jul 23 '21 at 15:02
  • 2
    _"undo things not to be undone"_ - These things would be all things. How can I really trust my source code to something that let me (or others) change the history. – StingyJack Aug 07 '21 at 18:36
  • 8
    Arguing against an `undo` command is artificial stodginess. Yes, you can effect this with a combination of `reflog`, `reset`, and `checkout`. The problem is that's a wholly unnatural expression of intent for anyone who doesn't do it routinely. Mercurial has `rollback` and it hasn't broken anything. Git should have something too. – dgc Oct 20 '21 at 19:35
  • 4
    You can install [git-extras](https://github.com/tj/git-extras) which are a set of git utility functions - includes the `git undo` command to undo the most recent commit. I use it all of the time when I just committed something (and haven't pushed yet) and need to add an unstaged file or change the commit comment. – Dr. Mike Hopper Jan 19 '22 at 17:39
  • 2
    For your case, you can simply do the git reset (if you haven't pushed to the branch). If you have already pushed to the branch then do git reset --hard HEAD^1 – Xab Ion Feb 17 '22 at 05:19
  • 1
    try with git diff + git apply – david grinstein Dec 02 '22 at 01:41
  • 1
    Maybe we could just improve/change the behaviour of the `git revert` command to actually remove the effects of a commit, rather than creating a revert commit. – Eduardo Pignatelli Jan 10 '23 at 16:30
  • 1
    "undo" is the most vague question in codebase management with git. You need to specify where you want your code to be. [git reset](https://git-scm.com/docs/git-reset) doc is a good starting point and reference. `git reset --mixed` is the default action for `git reset`, you should ponder upon the reason for this, thus you will have a clear expectation on codebase management before digging into git usage. – tinystone Mar 09 '23 at 01:10

105 Answers105

28258

Undo a commit & redo

$ git commit -m "Something terribly misguided" # (0: Your Accident)
$ git reset HEAD~                              # (1)
[ edit files as necessary ]                    # (2)
$ git add .                                    # (3)
$ git commit -c ORIG_HEAD                      # (4)
  1. 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.
  2. Make corrections to working tree files.
  3. git add anything that you want to include in your new commit.
  4. Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEAD; commit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the -C option.

Alternatively, to edit the previous commit (or just its commit message), commit --amend will add changes within the current index to the previous commit.

To remove (not revert) a commit that has been pushed to the server, rewriting history with git push origin main --force[-with-lease] is necessary. It's almost always a bad idea to use --force; prefer --force-with-lease instead, and as noted in the git manual:

You should understand the implications of rewriting history if you [rewrite history] has already been published.


Further Reading

You can use git reflog to determine the SHA-1 for the commit to which you wish to revert. Once you have this value, use the sequence of commands as explained above.


HEAD~ is the same as HEAD~1. The article What is the HEAD in git? is helpful if you want to uncommit multiple commits.

BestCoderBoy
  • 186
  • 13
Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
  • 588
    And if the commit was to the wrong branch, you may `git checkout theRightBranch` with all the changes stages. As I just had to do. – Frank Shearar Oct 05 '10 at 15:44
  • 577
    If you're working in DOS, instead of `git reset --soft HEAD^` you'll need to use `git reset --soft HEAD~1`. The ^ is a continuation character in DOS so it won't work properly. Also, `--soft` is the default, so you can omit it if you like and just say `git reset HEAD~1`. – Ryan Lundy Apr 13 '11 at 14:15
  • 160
    zsh users might get: `zsh: no matches found: HEAD^` - you need to escape ^ i.e. `git reset --soft HEAD\^` – tnajdek Feb 21 '13 at 17:47
  • 24
    The answer is not correct if, say by accident, `git commit -a` was issued when the `-a` should have been left out. In which case, it's better no leave out the `--soft` (which will result in `--mixed` which is the default) and then you can restage the changes you meant to commit. – dmansfield Jul 02 '14 at 21:19
  • 3
    This doesn't really serve as way to undo a set of changes those? This is more if you need to amend a change? – jterm Mar 14 '17 at 21:30
  • 8
    If you have already pushed your changes to a remote branch, and you do git reset as shown above, you will be behind the remote branch. In such a situation, it is preferable to use git revert which will add another commit which reverts the previous changes. More information [here](http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html) – user3613932 Apr 13 '17 at 18:08
  • 5
    It is almost a comprehensive answer. In case your 'last commit' === 'your first commit' — reset will do nothing but throw nice fatal message. In this case use `git update-ref -d HEAD`. – daGo Oct 06 '17 at 12:36
  • 2
    Also if you have too-large files that don't belong and cant complete your initial commits. you can delete .git, remove your too large files. git init and commit -m 'initial commit' and then push -u origin master – microsaurus_dex Mar 20 '18 at 03:27
  • 3
    **zsh** users should [turn off globbing](http://bewatermyfriend.org/p/2016/002/) with `noglob git` to get rid of this constant annoyance with caret `^` character. – Mr. Tao May 06 '18 at 10:40
  • 4
    - git reset --hard HEAD~1, will go back to one commit and delete all file git knows about, but not untracked files, since git got no idea of them. - git reset HEAD~1, will keep all the changes of the current commit,but make them untracked - git reset --soft HEAD~1, will keep your commited files staged and untracked files still untracked – briefy Nov 07 '18 at 08:51
  • 2
    I accidentally committed an entire folder. so I then ran 'git reset HEAD core/' which gave me this list 'Unstaged changes after reset:' (showing all my core folder/subfolder files). Then when I ran 'git status' all my "core"content was under the list heading "Changes not staged for commit:" which sounds good. I then added 'core' to my .gitignore. and ran 'git status' again, but the files kept appearing in the "not staged for commit" list. I'd rather git does not even see them but I can't figure out how to do that? – Auxiliary Joel Jul 28 '19 at 23:45
  • 53
    I've googled & hit this page about 50 times, and I always chuckle at the first line of code `git commit -m "Something terribly misguided"` – 100pic Aug 21 '19 at 04:25
  • 7
    Running the first command gives `fatal: ambiguous argument 'HEAD~': unknown revision or path not in the working tree.` – Ben Nov 08 '19 at 14:19
  • 2
    By accident I did `git commit -m '...' files` without first doing `git add files` and noticed that that commit and push worked fine. I guess git is now smart enough to do an add automatically when you use `git commit`. – thdoan Dec 11 '19 at 01:17
  • 2
    I keep forgetting, googling, and coming back to this answer. I'm done! `git config --global alias.undo 'reset --soft HEAD^'` lets you just type `git undo`. There are other answers with other reasons listed below, but this is by and far the most used one for me – chrisan Sep 16 '21 at 21:23
  • 1
    Hi, could this be combined with git stash to move the changes to another branch as well? For instance git reset head to undo the accidental commit (leaving the changes in place in the working tree as you said), git stash the changes, then checkout a different or new branch and git stash pop to bring in the changes, then add and commit? – Michael Wegter Mar 11 '22 at 22:34
  • Revert to previous commit: 1. git reset HEAD~ 2. git checkout – Sanjay Amin Jun 17 '22 at 00:31
  • 1
    Unclear if this command undo only the last action, and the changes will go back to being staged after it, or if everything gets lost. – Jonas Rosenqvist Sep 12 '22 at 19:07
  • @RyanLundy: Please correct your popular comment. --soft is not the default. --mixed is the default. – sondra.kinsey Aug 29 '23 at 17:12
  • @sondra.kinsey From long ago I had a correcting comment below it saying that in fact `--mixed` was the default, but it seems to have disappeared. Perhaps it was "helpfully" deleted by a moderator. Unfortunately there's no way to edit comments, so I can't fix the original. Still, whether `--soft` or `--mixed`, the important thing is that you're not losing work. – Ryan Lundy Aug 30 '23 at 18:33
12520

Undoing a commit is a little scary if you don't know how it works. But it's actually amazingly easy if you do understand. I'll show you the 4 different ways you can undo a commit.

Say you have this, where C is your HEAD and (F) is the state of your files.

   (F)
A-B-C
    ↑
  master

Option 1: git reset --hard

You want to destroy commit C and also throw away any uncommitted changes. You do this:

git reset --hard HEAD~1

The result is:

 (F)
A-B
  ↑
master

Now B is the HEAD. Because you used --hard, your files are reset to their state at commit B.

Option 2: git reset

Maybe commit C wasn't a disaster, but just a bit off. You want to undo the commit but keep your changes for a bit of editing before you do a better commit. Starting again from here, with C as your HEAD:

   (F)
A-B-C
    ↑
  master

Do this, leaving off the --hard:

git reset HEAD~1

In this case the result is:

   (F)
A-B-C
  ↑
master

In both cases, HEAD is just a pointer to the latest commit. When you do a git reset HEAD~1, you tell Git to move the HEAD pointer back one commit. But (unless you use --hard) you leave your files as they were. So now git status shows the changes you had checked into C. You haven't lost a thing!

Option 3: git reset --soft

For the lightest touch, you can even undo your commit but leave your files and your index:

git reset --soft HEAD~1

This not only leaves your files alone, it even leaves your index alone. When you do git status, you'll see that the same files are in the index as before. In fact, right after this command, you could do git commit and you'd be redoing the same commit you just had.

Option 4: you did git reset --hard and need to get that code back

One more thing: Suppose you destroy a commit as in the first example, but then discover you needed it after all? Tough luck, right?

Nope, there's still a way to get it back. Type this

git reflog

and you'll see a list of (partial) commit shas (that is, hashes) that you've moved around in. Find the commit you destroyed, and do this:

git checkout -b someNewBranchName shaYouDestroyed

You've now resurrected that commit. Commits don't actually get destroyed in Git for some 90 days, so you can usually go back and rescue one you didn't mean to get rid of.

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
  • 2
    @Kyralessa: If I do `git reset --hard HEAD^` twice, will the state shift to `(A)`? – dma_k Feb 25 '12 at 13:31
  • 1
    Doesn't work with OS x. - I get "ambiguous argument 'HEAD^' ... Unknow revision or path not in the working tree". Using he tilde version makes no difference. But git log and git status both appear to show there is a valid commit in place – Adam Jun 22 '12 at 10:53
  • 1
    @Kyralessa - yes, I think that might be the problem. In this case, I committed something I thought was small - and when I tried to Push, I found it was 400 MB of data (!) (a deep nested Resources folder containing video and music files). So, I need to undo the commit, but keep the source files, and I'll commit them later, when I have better net connection - or to a different repo. – Adam Jun 22 '12 at 12:35
  • 1
    My thanks also for the explanation. Question about this statement though (re --hard) : "your files are reset to their state at commit B". Say I had only committed some of my modifications, other files being intended for future commits. How much am I resetting? Just the committed files? Or do I reset my whole working set? – TwainJ Oct 30 '12 at 06:09
  • 69
    BEWARE! This might not do what you expect if your erroneous commit was a (fast-forward) merge! If your head is on a merge commit (ex: merged branch feature into master), `git reset --hard~1` will point the master branch to the last commit inside the feature branch. In this case the specific commit ID should be used instead of the relative command. – Chris Kerekes Feb 20 '13 at 18:46
  • 1
    Upon further thought this behaviour nay have been a result of merging the master branch into the feature branch first, testing and then (fast-forward) merging the feature branch into the master. – Chris Kerekes Feb 21 '13 at 14:05
  • 26
    Consider noting that the number in `HEAD~1` can be substituted to any positive integer, e.g. `HEAD~3`. It may seem obvious, but beginners (like me) are very careful when running git commands, so they may not want to risk messing something up by testing this stuff themselves. – Šime Vidas Aug 13 '13 at 14:37
  • 1
    Great tip. Just used it, though I think it's relevant to note that any tags associated with the deleted commit will continue to exist, even though it won't appear in gitk. Delete it with "git tag -d XXXXX" where XXXXX is the tag name. – Phlucious Oct 24 '13 at 21:54
  • 174
    Missing a crucial point: If the said commit was previously 'pushed' to the remote, any 'undo' operation, no matter how simple, will cause enormous pain and suffering to the rest of the users who have this commit in their local copy, when they do a 'git pull' in the future. So, if the commit was already 'pushed', do this instead: git revert git push origin : – FractalSpace Nov 08 '13 at 23:43
  • 36
    @FractalSpace, it won't cause "enormous pain and suffering." I've done a few force pushes when using Git with a team. All it takes is communication. – Ryan Lundy Nov 09 '13 at 00:00
  • 39
    @Kyralessa In my workplace, messing up entire team's workflow and then telling them how to fix sh*t is not called 'communication'. git history re-write is a destructive operation that results in trashing of parts of the repo. Insisting on its use, while clear and safe alternatives are available is simply irresponsible. – FractalSpace Nov 09 '13 at 03:02
  • 1
    @Kyralessa, I have a question about your answer. You say that "git reset --soft" "not only leaves your files alone, it even leaves your index alone. When you do git status, you'll see that the same files are in the index as before. In fact, right after this command, you could do git commit and you'd be redoing the same commit you just had." But if "git reset --soft" doesn't change the index, "git commit" wouldn't do anything. Do you mean "git commit -a" (assuming there had been no changes in the working directory beforehand) or am I missing something (likelier)? – Ellen Spertus Feb 20 '14 at 10:48
  • 3
    @espertus, perhaps one way to look at it is that there are three things working here: Your files, your index, and your history (that is, your branch pointer). Let's say you're at commit C (as above). Your files, index, and branch pointer match. If you use git reset --soft HEAD~1, your branch pointer moves back to B, but your files and index stay at their versions in C. If you use git reset --mixed HEAD~1, your branch pointer and index move back to B, but your files stay in their state at C. Then your files show changes but your index doesn't. git reset --hard HEAD~1 moves all three back. – Ryan Lundy Feb 20 '14 at 14:28
  • 4
    [Reset demystified](http://git-scm.com/blog/2011/07/11/reset.html) by Scott Chacon (GitHub CIO, _Pro Git_ author) explains and illustrates the `git reset` command and how to move the HEAD (`--soft`), update the index (`--mixed`, _default_) and update the working directory (`--hard`), from the bottom up. I've always used Kyralessa's answer as a cheat sheet, but Scott's blog post finally made it click and stick! – fspinnenhirn Aug 19 '14 at 03:13
  • 1
    @Kyralessa I see. But is it better to talk of "shas" than of "hashes"? The git man page mentions only hashes and "SHA-1 hashes". The question is rather: What improves the answer most? – Alfe Sep 13 '17 at 12:09
  • 2
    What is the difference between `git reset --hard HEAD~1` and `git reset --hard`, if what you need is to simply get rid of all of the changes you made after your latest commit? I always use `git reset --hard` and it takes me back to my latest commit. For an analogy, I feel that it is kind of closing an application without saving changes so that everything that was on RAM memory is lost, but what you had on ROM memory is kept, using your latest commit as the ROM memory in this analogy, and your changes that have not been committed as stuff in the RAM memory that has not been saved yet. – Jaime Montoya Sep 27 '17 at 23:35
  • 1
    Citing @poorva from comments in other posts below: 'To undo latest changes you can use git reset --hard , but if you have to hard remove last "n" commits you specify a SHA'. – Jaime Montoya Sep 28 '17 at 15:00
  • 1
    Can you rearrange the post to make the --soft the first suggestion shown? One of our engineers didn't read the full article and used --hard on a shared working directory, which luckily only cost us one day of work. - Thanks. P.S. Yes, we know using shared working directories are bad practice, but this isn't storing code, but puppet configuration. – ruckc Oct 24 '17 at 20:32
  • 2
    I'm trying git reset --soft HEAD~1 and I keep getting the following, why?: fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]' – gangelo Dec 19 '17 at 20:53
  • @gangelo, how many commits do you have in your repository? More than one? It's hard to reset back before _any_ commits, so I usually start a repo with a "dummy" commit (such as an empty .gitignore file) to get around this type of problem. – Ryan Lundy Dec 19 '17 at 21:05
  • @Kyralessa I only have 1 commit but it's not pushed because, oddly enough, I need to pull down my .gitignore file from my repository. I guess I can commit and apply the .gitignore after the fact, but I don't remember how to do that and remember it being a hassle. I only want to undo the commit I have to a point where if I do 'git status' I'll see all my files tracked, and ready to commit as if it never happened. – gangelo Dec 19 '17 at 21:28
  • @gangelo, have a look here for some ideas about how to revert that first commit: https://stackoverflow.com/questions/6632191/how-to-revert-initial-git-commit – Ryan Lundy Dec 20 '17 at 07:59
  • - git reset --hard HEAD~1, will go back to one commit and delete all file git knows about, but not untracked files, since git got no idea of them. - git reset HEAD~1, will keep all the changes of the current commit,but make them untracked - git reset --soft HEAD~1, will keep your commited files staged and untracked files still untracked – briefy Nov 07 '18 at 04:27
  • This is great. Super useful if your last commit was a "wip" but you want to re-organize into more meaningful commits, in which case use. `git reset --soft HEAD~1` – Pztar Jan 09 '19 at 20:20
  • 1
    As mentioned by @Kidburla, when using `git reset --hard HEAD~1` deletes the current changes that were not commited. It's a bit confusing because it seems that (F) is representing these changes and you keep (F) after `reset --hard`. There should be a warning or something to prevent people from deleting their changes. Or you could also represent the "uncommitted changes" in the examples. – Murilo May 13 '19 at 17:09
  • I don't think hard reset preserves the state of your files unless they were originally untracked. – Tormod Jan 03 '22 at 11:24
  • @RyanLundy in between the 3rd and 4th option should we add `git stash save "code reverted"` for save changed in stash list. Following Suggestion 3. git reset --soft 4. git stash save "code reverted" 5.git reset --hard – Omkesh Sajjanwar Jul 25 '22 at 13:04
  • 1
    @OmkeshSajjanwar You can add it in your own answer if you want to. Personally, I _never_ use `git stash`. Branches in Git are so easy to create, it makes no sense to use the stash instead of quickly creating a temporary branch to save work. – Ryan Lundy Jul 25 '22 at 15:03
  • NEVER EVER THINK OF RESETTING HARD IF YOU HAVE UNSTAGED CHANGES!!! A cool day turned horrible. Thanks to the considerate soul who added IDE backup feature as default. It saved my beautiful code and me! – Waleed93 Aug 05 '22 at 00:10
2665

There are two ways to "undo" your last commit, depending on whether or not you have already made your commit public (pushed to your remote repository):

How to undo a local commit

Let's say I committed locally, but now I want to remove that commit.

git log
    commit 101: bad commit    # Latest commit. This would be called 'HEAD'.
    commit 100: good commit   # Second to last commit. This is the one we want.

To restore everything back to the way it was prior to the last commit, we need to reset to the commit before HEAD:

git reset --soft HEAD^     # Use --soft if you want to keep your changes
git reset --hard HEAD^     # Use --hard if you don't care about keeping the changes you made

Now git log will show that our last commit has been removed.

How to undo a public commit

If you have already made your commits public, you will want to create a new commit which will "revert" the changes you made in your previous commit (current HEAD).

git revert HEAD

Your changes will now be reverted and ready for you to commit:

git commit -m 'restoring the file I removed by accident'
git log
    commit 102: restoring the file I removed by accident
    commit 101: removing a file we don't need
    commit 100: adding a file that we need

For more information, check out Git Basics - Undoing Things.

Community
  • 1
  • 1
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • 136
    I found this answer the clearest. `git revert HEAD^` is not the previous, is the previous of the previous. I did : `git revert HEAD` and then push again and it worked :) – nacho4d Jul 14 '11 at 08:32
  • 9
    If Git asks you "More?" when you try these commands, use the alternate syntax on this answer: https://stackoverflow.com/a/14204318/823470 – tar Mar 05 '20 at 15:50
  • `revert` deleted some files I add added to my repo. Use it with caution! – carloswm85 Jul 31 '21 at 22:25
1922

Add/remove files to get things the way you want:

git rm classdir
git add sourcedir

Then amend the commit:

git commit --amend

The previous, erroneous commit will be edited to reflect the new index state - in other words, it'll be like you never made the mistake in the first place.

Note that you should only do this if you haven't pushed yet. If you have pushed, then you'll just have to commit a fix normally.

Vikrant
  • 4,920
  • 17
  • 48
  • 72
bdonlan
  • 224,562
  • 31
  • 268
  • 324
1265

This will add a new commit which deletes the added files.

git rm yourfiles/*.class
git commit -a -m "deleted all class files in folder 'yourfiles'"

Or you can rewrite history to undo the last commit.

Warning: this command will permanently remove the modifications to the .java files (and any other files) that you committed -- and delete all your changes from your working directory:

git reset --hard HEAD~1

The hard reset to HEAD-1 will set your working copy to the state of the commit before your wrong commit.

ChrisW
  • 54,973
  • 13
  • 116
  • 224
Lennart Koopmann
  • 20,313
  • 4
  • 26
  • 33
  • 28
    `git commit -a -m ""` or `git commit -am ""` naturally! :] – trejder Jun 21 '14 at 16:31
  • Another 'shortcut' use of stash; if you want to unstage everything (undo git add), just `git stash`, then `git stash pop` – seanriordan08 Dec 08 '15 at 22:30
  • 12
    Gosh... this answer should be deleted. `git reset --hard HEAD-1` is incredibly dangerous - it's not just "undoing the commit", it also delete all of your changes, which is not what OP asked for. I unfortunately applied this answer (which StackOverflow for no reason shows first than the accepted one with 26k upvotes), and now will struggle to recover all of my changes. – Jack Jun 07 '22 at 13:19
  • 3
    For those who did not read and just ran the above command like me, I hope you learned your lesson now XD... To undo command, ```git reflog``` to find the discarded commit and run ```git reset --hard $1``` where ```$1``` is your discarded commit – seantsang Aug 11 '22 at 04:10
935

To change the last commit

Replace the files in the index:

git rm --cached *.class
git add *.java

Then, if it's a private branch, amend the commit:

git commit --amend

Or, if it's a shared branch, make a new commit:

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

(To change a previous commit, use the awesome interactive rebase.)


ProTip™: Add *.class to a gitignore to stop this happening again.


To revert a commit

Amending a commit is the ideal solution if you need to change the last commit, but a more general solution is reset.

You can reset Git to any commit with:

git reset @~N

Where N is the number of commits before HEAD, and @~ resets to the previous commit.

Instead of amending the commit, you could use:

git reset @~
git add *.java
git commit -m "Add .java files"

Check out git help reset, specifically the sections on --soft --mixed and --hard, for a better understanding of what this does.

Reflog

If you mess up, you can always use the reflog to find dropped commits:

$ git reset @~
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~
2c52489 HEAD@{1}: commit: added some .class files
$ git reset 2c52489
... and you're back where you started

Zoe
  • 27,060
  • 21
  • 118
  • 148
Zaz
  • 46,476
  • 14
  • 84
  • 101
  • 6
    For those reading in future - please note that `git revert` is a separate command - which basically 'resets' a single commimt. – BenKoshy Aug 08 '18 at 07:11
  • Adding to the reply of @BenKoshy - please also note that `git revert` will create a new commit that inverses the given changes. It is a safer alternative to `git reset`. – gsan Nov 17 '22 at 22:24
823

Use git revert <commit-id>.

To get the commit ID, just use git log.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jaco Pretorius
  • 24,380
  • 11
  • 62
  • 94
  • 22
    What does that mean, cherry pick the commit? In my case, I was on the wrong branch when I edited a file. I committed it then realized I was in the wrong branch. Using "git reset --soft HEAD~1" got me back to just before the commit, but now if I checkout the correct branch, how do I undo the changes to the file in wrong branch but instead make them (in the same named file) in the correct branch? – astronomerdave Jan 13 '15 at 22:05
  • I just utilized `git revert commit-id` worked like a charm. Of course then you will need to push your changes. – Casey Robinson Jan 25 '16 at 21:07
  • 11
    I believe that would be `git cherry-pick <>` @astronomerdave. From, Mr. Almost-2-Years-Late-to-the-Party. – Tom Howard Oct 20 '16 at 18:19
  • @Kris: Instead of cherry-pick use rebase. Because it is advanced cherry-picking – Eugen Konkov Nov 10 '18 at 09:38
  • 2
    I'd use revert only if I've already pushed my commit. Otherwise, reset is a better option. Don't forget that revert creates a new commit, and usually this is not the goal. – Hola Soy Edu Feliz Navidad Feb 06 '20 at 12:40
682

If you are planning to undo a local commit entirely, whatever you change you did on the commit, and if you don't worry anything about that, just do the following command.

git reset --hard HEAD^1

(This command will ignore your entire commit and your changes will be lost completely from your local working tree). If you want to undo your commit, but you want your changes in the staging area (before commit just like after git add) then do the following command.

git reset --soft HEAD^1

Now your committed files come into the staging area. Suppose if you want to upstage the files, because you need to edit some wrong content, then do the following command

git reset HEAD

Now committed files to come from the staged area into the unstaged area. Now files are ready to edit, so whatever you change, you want to go edit and added it and make a fresh/new commit.

More (link broken) (Archived version)

riQQ
  • 9,878
  • 7
  • 49
  • 66
Madhan Ayyasamy
  • 15,600
  • 3
  • 19
  • 18
  • 19
    @SMR, In your example, all are pointing into current HEAD only. HEAD^ = HEAD^1. As well as HEAD^1 = HEAD~1. When you use HEAD~2, there is a difference between ~ and ^ symbols. If you use ~2 means “the first parent of the first parent,” or “the grandparent”. – Madhan Ayyasamy Dec 14 '15 at 15:34
  • git reset --hard HEAD^1 gives me this error "fatal: ambiguous argument 'HEAD1': unknown revision or path not in the working tree." – Rob Mosher Dec 20 '20 at 10:55
613

If you have Git Extras installed, you can run git undo to undo the latest commit. git undo 3 will undo the last three commits.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nickf
  • 537,072
  • 198
  • 649
  • 721
576

I wanted to undo the latest five commits in our shared repository. I looked up the revision id that I wanted to rollback to. Then I typed in the following.

prompt> git reset --hard 5a7404742c85
HEAD is now at 5a74047 Added one more page to catalogue
prompt> git push origin master --force
Total 0 (delta 0), reused 0 (delta 0)
remote: bb/acl: neoneye is allowed. accepted payload.
To git@bitbucket.org:thecompany/prometheus.git
 + 09a6480...5a74047 master -> master (forced update)
prompt>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
neoneye
  • 50,398
  • 25
  • 166
  • 151
  • 33
    Rewriting history on a shared repository is generally a very bad idea. I assume you know what you're doing, I just hope future readers do too. – Brad Koch Dec 07 '12 at 16:02
  • Yes rollback is dangerous. Make sure that your working copy is in the desired state before you push. When pushing then the unwanted commits gets deleted permanently. – neoneye Dec 08 '12 at 14:14
  • 9
    "Just like in the real world, if you want to rewrite history, you need a conspiracy: everybody has to be 'in' on the conspiracy (at least everybody who knows about the history, i.e. everybody who has ever pulled from the branch)." Source: http://stackoverflow.com/a/2046748/334451 – Mikko Rantalainen Aug 07 '13 at 10:10
539

I prefer to use git rebase -i for this job, because a nice list pops up where I can choose the commits to get rid of. It might not be as direct as some other answers here, but it just feels right.

Choose how many commits you want to list, then invoke like this (to enlist last three)

git rebase -i HEAD~3

Sample list

pick aa28ba7 Sanity check for RtmpSrv port
pick c26c541 RtmpSrv version option
pick 58d6909 Better URL decoding support

Then Git will remove commits for any line that you remove.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zombo
  • 1
  • 62
  • 391
  • 407
506

How to fix the previous local commit

Use git-gui (or similar) to perform a git commit --amend. From the GUI you can add or remove individual files from the commit. You can also modify the commit message.

How to undo the previous local commit

Just reset your branch to the previous location (for example, using gitk or git rebase). Then reapply your changes from a saved copy. After garbage collection in your local repository, it will be like the unwanted commit never happened. To do all of that in a single command, use git reset HEAD~1.

Word of warning: Careless use of git reset is a good way to get your working copy into a confusing state. I recommend that Git novices avoid this if they can.

How to undo a public commit

Perform a reverse cherry pick (git-revert) to undo the changes.

If you haven't yet pulled other changes onto your branch, you can simply do...

git revert --no-edit HEAD

Then push your updated branch to the shared repository.

The commit history will show both commits, separately.


Advanced: Correction of the private branch in public repository

This can be dangerous -- be sure you have a local copy of the branch to repush.

Also note: You don't want to do this if someone else may be working on the branch.

git push --delete (branch_name) ## remove public version of branch

Clean up your branch locally then repush...

git push origin (branch_name)

In the normal case, you probably needn't worry about your private-branch commit history being pristine. Just push a followup commit (see 'How to undo a public commit' above), and later, do a squash-merge to hide the history.

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
  • 13
    `gitk --all $(git reflog | cut -c1-7)&` may be helpful for finding the previous revision if you want to undo an '--amend' commit. – Brent Bradburn Oct 18 '14 at 23:38
  • 8
    It should be noted that if you're attempting to remove secret information before pushing to a shared repository, doing a revert won't help you, because the information will still be in the history in the previous commit. If you want to ensure the change is never visible to others you need to use `git reset` – Jherico Sep 04 '15 at 04:52
  • Correcting a private branch in remote repository can also be done by simply `git push origin (branch_name) --force` – Brent Bradburn Sep 07 '18 at 12:09
418

If you want to permanently undo it and you have cloned some repository.

The commit id can be seen by:

git log 

Then you can do like:

git reset --hard <commit_id>

git push origin <branch_name> -f
Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
poorva
  • 1,726
  • 1
  • 17
  • 15
  • What if you do not use "" and simply use "git reset --hard"? I typically just want to get rid of my latest updates that I have not committed yet and got back to the latest commit I made, and I always use "git reset --hard". – Jaime Montoya Sep 27 '17 at 23:30
  • 7
    @JaimeMontoya To undo latest changes you can use `git reset --hard` , but if you have to hard remove last "n" commits you specify a SHA – poorva Sep 28 '17 at 13:10
  • Worked like a charm. The branch being reset ('master') was not checked-out by any one, so no chance of any conflict. – Gsv Apr 24 '23 at 12:07
411

If you have committed junk but not pushed,

git reset --soft HEAD~1

HEAD~1 is a shorthand for the commit before head. Alternatively you can refer to the SHA-1 of the hash if you want to reset to. --soft option will delete the commit but it will leave all your changed files "Changes to be committed", as git status would put it.

If you want to get rid of any changes to tracked files in the working tree since the commit before head use "--hard" instead.

OR

If you already pushed and someone pulled which is usually my case, you can't use git reset. You can however do a git revert,

git revert HEAD

This will create a new commit that reverses everything introduced by the accidental commit.

Johan Karlsson
  • 1,136
  • 1
  • 14
  • 37
santos_mgr
  • 37
  • 1
  • 2
  • 7
  • 8
    Probably worth mentioning that instead of `HEAD~1` you could use the actual hash as displayed by `git log --stat` or by `git reflog` - useful when you need to 'undo' more than one commit. – ccpizza Dec 07 '14 at 00:38
351

On SourceTree (GUI for GitHub), you may right-click the commit and do a 'Reverse Commit'. This should undo your changes.

On the terminal:

You may alternatively use:

git revert

Or:

git reset --soft HEAD^ # Use --soft if you want to keep your changes.
git reset --hard HEAD^ # Use --hard if you don't care about keeping your changes.
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Varun Parakh
  • 221
  • 1
  • 4
  • 10
322

A single command:

git reset --soft 'HEAD^' 

It works great to undo the last local commit!

Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101
  • 17
    I needed to write git reset --soft "HEAD^" with double quotes, because I write it from Windows command prompt. – Ena Apr 23 '14 at 09:13
302

Just reset it doing the command below using git:

git reset --soft HEAD~1

Explain: what git reset does, it's basically reset to any commit you'd like to go back to, then if you combine it with --soft key, it will go back, but keep the changes in your file(s), so you get back to the stage which the file was just added, HEAD is the head of the branch and if you combine with ~1 (in this case you also use HEAD^), it will go back only one commit which what you want...

I create the steps in the image below in more details for you, including all steps that may happens in real situations and committing the code:

How to undo the last commits in Git?

Alireza
  • 100,211
  • 27
  • 269
  • 172
295

"Reset the working tree to the last commit"

git reset --hard HEAD^ 

"Clean unknown files from the working tree"

git clean    

see - Git Quick Reference

NOTE: This command will delete your previous commit, so use with caution! git reset --hard is safer.

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
Ravi_Parmar
  • 12,319
  • 3
  • 25
  • 36
275

How to undo the last Git commit?

To restore everything back to the way it was prior to the last commit, we need to reset to the commit before HEAD.

  1. If you don't want to keep your changes that you made:

    git reset --hard HEAD^
    
  2. If you want to keep your changes:

    git reset --soft HEAD^
    

Now check your git log. It will show that our last commit has been removed.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ranjithkumar Ravi
  • 3,352
  • 2
  • 20
  • 22
225

Use reflog to find a correct state

git reflog

reflog before REFLOG BEFORE RESET

Select the correct reflog (f3cb6e2 in my case) and type

git reset --hard f3cb6e2

After that the repo HEAD will be reset to that HEADid reset effect LOG AFTER RESET

Finally the reflog looks like the picture below

reflog after REFLOG FINAL

Shubham Chaudhary
  • 47,722
  • 9
  • 78
  • 80
197

First run:

git reflog

It will show you all the possible actions you have performed on your repository, for example, commit, merge, pull, etc.

Then do:

git reset --hard ActionIdFromRefLog
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
U. Ali
  • 151
  • 2
  • 3
  • 7
181

Undo 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 last commit to new commit:

git commit --amend -m "message"

It will replace the last commit with the new commit.

dippas
  • 58,591
  • 15
  • 114
  • 126
akshay_rahar
  • 1,661
  • 2
  • 18
  • 20
180

Another way:

Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree I right-clicked on the and selected "Reset BRANCHNAME to this commit".

Then navigate to your repository's local directory and run this command:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f --tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME

This will erase all commits after the current one in your local repository but only for that one branch.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
CommaToast
  • 11,370
  • 7
  • 54
  • 69
168

Type git log and find the last commit hash code and then enter:

git reset <the previous co>
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
user853293
  • 36
  • 1
  • 2
  • 6
164

In my case I accidentally committed some files I did not want to. So I did the following and it worked:

git reset --soft HEAD^
git rm --cached [files you do not need]
git add [files you need]
git commit -c ORIG_HEAD

Verify the results with gitk or git log --stat

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
egridasov
  • 819
  • 1
  • 8
  • 7
162

WHAT TO USE, reset --soft or reset --hard?

I am just adding two cents for @Kyralessa's answer:

If you are unsure what to use go for --soft (I used this convention to remember it --soft for safe).

Why?

If you choose --hard by mistake you will LOSE your changes as it wasn't before. If you choose --soft by mistake you can achieve the same results of --hard by applying additional commands

git reset HEAD file.html
git checkout -- file.html

Full example

echo "some changes..." > file.html
git add file.html
git commit -m "wrong commit"

# I need to reset
git reset --hard HEAD~1 (cancel changes)
# OR
git reset --soft HEAD~1 # Back to staging
git reset HEAD file.html # back to working directory
git checkout -- file.html # cancel changes

Credits goes to @Kyralessa.

amd
  • 20,637
  • 6
  • 49
  • 67
  • 9
    The very useful description about differences `--soft` VS `--hard` https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/ – Eugen Konkov Dec 15 '16 at 16:29
  • 3
    One doesn't really lose the commits on a `--hard` reset as they will be available in the ref log for 30 days `git reflog`. – Todd Sep 11 '17 at 14:10
157

Simple, run this in your command line:

git reset --soft HEAD~ 
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
code-8
  • 54,650
  • 106
  • 352
  • 604
150

There are many ways to do it:

Git command to undo the last commit/ previous commits:

Warning: Do Not use --hard if you do not know what you are doing. --hard is too dangerous, and it might delete your files.

Basic command to revert the commit in Git is:

$ git reset --hard <COMMIT -ID>

or

$ git reset --hard HEAD~<n>

COMMIT-ID: ID for the commit

n: is the number of last commits you want to revert

You can get the commit id as shown below:

$ **git log --oneline**

d81d3f1 function to subtract two numbers

be20eb8 function to add two numbers

bedgfgg function to multiply two numbers

where d81d3f1 and be20eb8 are commit id.

Now, let's see some cases:

Suppose you want to revert the last commit 'd81d3f1'. Here are two options:

$ git reset --hard d81d3f1

or

$ git reset --hard HEAD~1

Suppose you want to revert the commit 'be20eb8':

$ git reset --hard be20eb8

For more detailed information, you can refer to and try out some other commands too for resetting the head to a specified state:

$ git reset --help
Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Spyder
  • 894
  • 2
  • 14
  • 18
  • 11
    `git reset --hard HEAD~1` is **too dangerous**! This will not just 'cancel last commit', but will revert repo completely back to the previous commit. So you will LOOSE all changes committed in the last commit! – Arnis Juraga Mar 21 '17 at 12:09
  • You right, to undo this you can use `git push -f HEAD@{1}:` – Benny Apr 24 '17 at 13:07
  • 1
    Unfortunately, I use --hard, and my files are deleted! I did not check the comment first because it is collapsed. Do not use --hard if you do not know what you are doing! – anonymous Aug 19 '18 at 13:53
147

For a local commit

git reset --soft HEAD~1

or if you do not remember exactly in which commit it is, you might use

git rm --cached <file>

For a pushed commit

The proper way of removing files from the repository history is using git filter-branch. That is,

git filter-branch --index-filter 'git rm --cached <file>' HEAD

But I recomnend you use this command with care. Read more at git-filter-branch(1) Manual Page.

geoom
  • 6,279
  • 2
  • 26
  • 37
147

There are two main scenarios

You haven't pushed the commit yet

If the problem was extra files you commited (and you don't want those on repository), you can remove them using git rm and then commiting with --amend

git rm <pathToFile>

You can also remove entire directories with -r, or even combine with other Bash commands

git rm -r <pathToDirectory>
git rm $(find -name '*.class')

After removing the files, you can commit, with --amend option

git commit --amend -C HEAD # the -C option is to use the same commit message

This will rewrite your recent local commit removing the extra files, so, these files will never be sent on push and also will be removed from your local .git repository by GC.

You already pushed the commit

You can apply the same solution of the other scenario and then doing git push with the -f option, but it is not recommended since it overwrites the remote history with a divergent change (it can mess your repository).

Instead, you have to do the commit without --amend (remember this about -amend`: That option rewrites the history on the last commit).

Elliot A.
  • 1,511
  • 2
  • 14
  • 19
dseminara
  • 11,665
  • 2
  • 20
  • 22
142

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

git reset --hard HEAD~1
Zaz
  • 46,476
  • 14
  • 84
  • 101
thestar
  • 4,959
  • 2
  • 28
  • 22
  • 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. – cr7pt0gr4ph7 Nov 24 '14 at 22:35
  • 6
    If you happen to do this by accident, not all is lost, though. See http://stackoverflow.com/questions/10099258/how-can-i-recover-a-lost-commit-in-git, http://stackoverflow.com/questions/15479501/git-commit-lost-after-reset-hard-not-found-by-fsck-not-in-reflog and http://stackoverflow.com/questions/7374069/undo-git-reset-hard/7376959. – cr7pt0gr4ph7 Nov 24 '14 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. – Yunus Nedim Mehel Mar 09 '15 at 09: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`. – cr7pt0gr4ph7 Sep 13 '16 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). – cr7pt0gr4ph7 Sep 13 '16 at 21:22
  • This is terrible advice. This doesn't just reset your remote, this deletes the actual files from the folder you are doing. This was not clear at all to me, and I thought you were saying you were simply resetting the git head, not resetting your current files to what is in the repository. If my notebooks from yesterday were not in my RAM I would have lost everything I did yesterday. – stidmatt Jan 25 '19 at 22:41
134

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

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
iOS Coder
  • 39
  • 1
  • 2
  • 4
99

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
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umar Hayat
  • 4,300
  • 1
  • 12
  • 27
98

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

Ali Motameni
  • 2,567
  • 3
  • 24
  • 34
88

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.
Zoe
  • 27,060
  • 21
  • 118
  • 148
Carl
  • 43,122
  • 10
  • 80
  • 104
83

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
Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58
80

You can use:

git reset HEAD@{1}

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jade Han
  • 1,185
  • 5
  • 15
  • 36
75

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohit
  • 776
  • 7
  • 13
72

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

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
steven
  • 529
  • 6
  • 15
67

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

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
65

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
FraK
  • 919
  • 1
  • 13
  • 21
64

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.

Prajwal
  • 246
  • 1
  • 5
  • 16
Ankit Patidar
  • 2,731
  • 1
  • 14
  • 22
61

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alexandr
  • 5,460
  • 4
  • 40
  • 70
59

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).

Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
mfathy00
  • 1,601
  • 1
  • 13
  • 28
  • Be **extra** careful when reverting merge commits. You may lose your commits. Read about what Linus says about that: https://www.kernel.org/pub/software/scm/git/docs/howto/revert-a-faulty-merge.html – Eugen Konkov Dec 15 '16 at 16:25
  • Note that for git reset , 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 07 '22 at 15:25
57

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).

Paolo
  • 21,270
  • 6
  • 38
  • 69
KawaiKx
  • 9,558
  • 19
  • 72
  • 111
52

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...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
52

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stipe
  • 480
  • 5
  • 18
  • 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 '20 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 '21 at 16:29
51

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.

Community
  • 1
  • 1
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • 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 – Chaitanya Bapat Oct 30 '18 at 19:18
48

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
Jaimil Patel
  • 1,301
  • 6
  • 13
Ankit Tiwari
  • 41
  • 2
  • 6
46

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Alisa
  • 2,892
  • 3
  • 31
  • 44
45

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

Prajwal
  • 246
  • 1
  • 5
  • 16
V V
  • 774
  • 1
  • 9
  • 29
41

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yahs Hef
  • 797
  • 9
  • 24
41

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ioopl
  • 1,735
  • 19
  • 19
  • 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 HEAD is now at 5456cea... Need to delete Exclusions.xslt from Documentation folder. - Delete What should i do after this – cSharma May 22 '19 at 14:02
35

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>
Zoe
  • 27,060
  • 21
  • 118
  • 148
Paras Korat
  • 2,011
  • 2
  • 18
  • 36
32

Use this command

git checkout -b old-state 0d1d7fc32
32

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Montresor
  • 806
  • 6
  • 22
31

Use this command:

git checkout -b old-state number_commit
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fadid
  • 1,250
  • 15
  • 16
30

You can always do a git checkout <SHA code> of the previous version and then commit again with the new code.

Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
shreshta bm
  • 304
  • 4
  • 11
29

You can undo your Git commits in two ways: First is you can use git revert, if you want to keep your commit history:

git revert HEAD~3
git revert <hashcode of commit>

Second is you can use git reset, which would delete all your commit history and bring your head to commit where you want it.

git reset <hashcode of commit>
git reset HEAD~3

You can also use the --hard keyword if any of it starts behaving otherwise. But, I would only recommend it until it's extremely necessary.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shwetank
  • 374
  • 1
  • 6
  • 20
29
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abubakr Elghazawy
  • 977
  • 14
  • 21
29

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.

27

For sake of completeness, I will give the one glaringly obvious method that was overlooked by the previous answers.

Since the commit was not pushed, the remote was unchanged, so:

  1. Delete the local repository.
  2. Clone the remote repository.

This is sometimes necessary if your fancy Git client goes bye-bye (looking at you, egit).

Don't forget to re-commit your saved changes since the last push.

Dominic Cerisano
  • 3,522
  • 1
  • 31
  • 44
27

Here is site: Oh shit, git!.

Here are many recipes how to undo things in Git. Some of them:

Oh shit, I need to change the message on my last commit!

git commit --amend
# follow prompts to change the commit message

Oh shit, I accidentally committed something to master that should have been on a brand new branch!

# Create a new branch from the current state of master
git branch some-new-branch-name
# Remove the commit from the master branch
git reset HEAD~ --hard
git checkout some-new-branch-name
# Your commit lives in this branch now :)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
27

You can undo your commits from the local repository. Please follow the below scenario.

In the below image I check out the 'test' branch (using Git command git checkout -b test) as a local and check status (using Git command git status) of local branch that there is nothing to commit.

Enter image description here

In the next image image you can see here I made a few changes in Filter1.txt and added that file to the staging area and then committed my changes with some message (using Git command git commit -m "Doing commit to test revert back").

"-m is for commit message"

Enter image description here

In the next image you can see your commits log whatever you have made commits (using Git command git log).

Enter image description here

So in the above image you can see the commit id with each commit and with your commit message now whatever commit you want to revert back or undo copy that commit id and hit the below Git command, git revert {"paste your commit id"}. Example:

git revert 9ca304ed12b991f8251496b4ea452857b34353e7

Enter image description here

I have reverted back my last commit. Now if you check your Git status, you can see the modified file which is Filter1.txt and yet to commit.

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raj Rusia
  • 728
  • 10
  • 15
27

The simplest way to undo the last commit is

git reset HEAD^

This will bring the project state before you have made the commit.

Arun Karnawat
  • 575
  • 10
  • 21
26

I have found this site which describes how to undo things that you have committed into the repository.

Some commands:

git commit --amend        # Change last commit
git reset HEAD~1 --soft   # Undo last commit
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
26

Reference: How to undo last commit in Git?

If you have Git Extensions installed you can easily undo/revert any commit (you can download Git Extensions from here).

Open Git Extensions, right click on the commit you want to revert then select "Revert commit".

Git Extensions screen shot

A popup will be opened (see the screenshot below)

Revert commit popup

Select "Automatically create a commit" if you want to directly commit the reverted changes or if you want to manually commit the reverted changes keep the box un-selected and click on "Revert this commit" button.

tagurit
  • 494
  • 5
  • 13
Ranadheer Reddy
  • 4,202
  • 12
  • 55
  • 77
25

The difference between git reset --mixed, --soft and --hard

Prerequisite: When a modification to an existing file in your repository is made, this change is initially considered as unstaged. In order to commit the changes, it needs to be staged which means adding it to the index using git add. During a commit operation, the files that are staged gets added to an index.

Let's take an example:

- A - B - C (master)

HEAD points to C and the index matches C.

--soft

  • When we execute git reset --soft B with the intention of removing the commit C and pointing the master/HEAD to B.
  • The master/HEAD will now point to B, but the index still has changed from C.
  • When executing git status you could see the files indexed in commit C as staged.
  • Executing a git commit at this point will create a new commit with the same changes as C

--mixed

  • Execute git reset --mixed B.
  • On execution, master/HEAD will point to B and the index is also modified to match B because of the mixed flag used.
  • If we run git commit at this point, nothing will happen since the index matches HEAD.
  • We still have the changes in the working directory, but since they're not in the index, git status shows them as unstaged.
  • To commit them, you would git add and then commit as usual.

--hard

  • Execute git reset --hard B
  • On execution, master/HEAD will point to B and modifies your working directory
  • The changes added in C and all the uncommitted changes will be removed.
  • Files in the working copy will match the commit B, this will result in loosing permanently all changes which were made in commit C plus uncommitted changes

Hope this comparison of flags that are available to use with git reset command will help someone to use them wisely. Refer these for further details link1 & link2

Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
25

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

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 it's 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 to go back

This will checkout the 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.

enter image description here


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 history as well.

# Add a 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

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
24

I validate an efficient method proposed, and here is a concrete example using it:

In case you want to permanently undo/cancel your last commit (and so on, one by one, as many as you want) three steps:

1: Get the id = SHA of the commit you want to arrive on with, of course

$ git log

2: Delete your previous commit with

$ git reset --hard 'your SHA'

3: Force the new local history upon your origin GitHub with the -f option (the last commit track will be erased from the GitHub history)

$ git push origin master -f

Example

$ git log

Last commit to cancel

commit e305d21bdcdc51d623faec631ced72645cca9131 (HEAD -> master, origin/master, origin/HEAD)
Author: Christophe <blabla@bla.com>
Date:   Thu Jul 30 03:42:26 2020 +0200

U2_30 S45; updating files package.json & yarn.lock for GitHub Web Page from docs/CV_Portfolio...

Commit we want now on HEAD

commit 36212a48b0123456789e01a6c174103be9a11e61
Author: Christophe <blabla@bla.com>
Date:   Thu Jul 30 02:38:01 2020 +0200

First commit, new title

Reach the commit before by deleting the last one

$ git reset --hard 36212a4

HEAD is now at 36212a4 First commit, new title

Check it's OK

$ git log

commit 36212a48b0123456789e01a6c174103be9a11e61 (HEAD -> master)
Author: Christophe <blabla@bla.com>
Date:   Thu Jul 30 02:38:01 2020 +0200

    First commit, new title

$ git status

On branch master
Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
 (use "git pull" to update your local branch)

nothing to commit, working tree clean

Update your history on the Git(Hub)

$ git push origin master -f

Total 0 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/ GitUser bla bla/React-Apps.git
 + e305d21...36212a4 master -> master (forced update)

Check it's all right

$ git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
Zoe
  • 27,060
  • 21
  • 118
  • 148
CyberChris
  • 66
  • 1
  • 4
23

HEAD:

Before reset commit we should know about HEAD... HEAD is nothing but your current state in your working directory. It is represented by a commit number.

Git commit:

Each change assigned under a commit which is represented by a unique tag. Commits can't be deleted. So if you want your last commit, you can simply dive into it using git reset.

You can dive into the last commit using two methods:

Method 1: (if you don't know the commit number, but want to move onto the very first)

git reset HEAD~1  # It will move your head to last commit

Method 2: (if you know the commit you simply reset onto your known commit)

git reset 0xab3 # Commit number

Note: if you want to know a recent commit try git log -p -1

Here is the graphical representation:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
21

Just use git reset --hard <last good SHA> to reset your changes and give new commit. You can also use git checkout -- <bad filename>.

hubot
  • 393
  • 5
  • 18
20

If you would like to eliminate the wrong files you should do

git reset --soft <your_last_good_commit_hash_here> Here, if you do git status, you will see the files in the staging area. You can select the wrong files and take them down from the staging area.

Like the following.

git reset wrongFile1 wrongFile2 wrongFile3

You can now just add the files that you need to push,

git add goodFile1 goodFile2

Commit them

git commit -v or git commit -am "Message"

And push

git push origin master

However, if you do not care about the changed files you can hard reset to previous good commit and push everything to the server.

By

git reset --hard <your_last_good_commit_hash_here>

git push origin master

If you already published your wrong files to the server, you can use the --force flag to push to the server and edit the history.

git push --force origin master

Zoe
  • 27,060
  • 21
  • 118
  • 148
nPcomp
  • 8,637
  • 2
  • 54
  • 49
20
git reset --soft HEAD~1

git status

Output

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 ..." to unstage) new file: file1

git log --oneline --graph

Output

  • 90f8bb1 (HEAD -> master) Second commit \
  • 7083e29 Initial repository commit \
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arslan
  • 1,064
  • 10
  • 19
19

Before picking specific tools (commands), please pick what you need rather than blindly running commands.

Amending the commit

  • Just in case you want to edit your last commit, there is a command.

  • Advantage: It allows you to correct the last commit's message as well as add more changes to it.

    git commit --amend
    

Resetting the Commit

  • Really want to undo the last commit (because of massive changes or you want to discard it all).

  • Advantage: The reset command will return to the one before the current revision, effectively making the last commit undone.

A. Soft Reset

Advantage: A soft flag. It guarantees the preservation of modifications made in undone revisions. The changes appear in your working copy as uncommitted local modifications once you run the command.

git reset --soft HEAD~1

B. Hard Reset

Advantage: 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

Undo last commit but keep changes made to the files

Advantage:

This command will tell Git to advance the HEAD pointer back one commit. The files' modifications won't be impacted, though. Now, if you run git status, you ought to still be able to view the local file changes.

git reset HEAD~1

Use according to your needs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muhammad Ali
  • 956
  • 3
  • 15
  • 20
18

In IntelliJ IDEA you can just open the Git repository log by pressing Alt+9, right mouse button click at some tag from the commits list, and select: "Reset Current Branch to Here...".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
18

Rebasing and dropping commits are the best when you want to keep the history clean useful when proposing patches to a public branch etc.

If you have to drop the topmost commit then the following one-liner helps

git rebase --onto HEAD~1 HEAD

But if you want to drop 1 of many commits you did say

a -> b -> c -> d -> master

and you want to drop commit 'c'

git rebase --onto b c

This will make 'b' as the new base of 'd' eliminating 'c'

Yoon5oo
  • 496
  • 5
  • 11
Khem
  • 1,162
  • 8
  • 8
18

What I do each time I need to undo a commit/commits are:

  1. git reset HEAD~<n> // the number of last commits I need to undo

  2. git status // optional. All files are now in red (unstaged).

  3. Now, I can add & commit just the files that I need:

  • git add <file names> & git commit -m "message" -m "details"
  1. Optional: I can rollback the changes of the rest files, if I need, to their previous condition, with checkout:
  • git checkout <filename>
  1. if I had already pushed it to remote origin, previously:
  • git push origin <branch name> -f // use -f to force the push.
Zoe
  • 27,060
  • 21
  • 118
  • 148
Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
17

enter image description here

Assuming you're working in Visual Studio, if you go in to your branch history and look at all of your commits, simply select the event prior to the commit you want to undo, right-click it, and select Revert. Easy as that.

Siraf
  • 1,133
  • 9
  • 24
Uchiha Itachi
  • 1,251
  • 1
  • 16
  • 42
16

To undo the last local commit, without throwing away its changes, I have this handy alias in ~/.gitconfig

[alias]
  undo = reset --soft HEAD^

Then I simply use git undo which is super-easy to remember.

Michał Szajbe
  • 8,830
  • 3
  • 33
  • 39
15

Find the last commit hash code by seeing the log by:

git log

Then

git reset <the previous co>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Praveen
  • 35
  • 1
  • 11
13

Replace your local version, including your changes with the server version. These two lines of code will force Git to pull and overwrite local.

Open a command prompt and navigate to the Git project root. If you use Visual Studio, click on Team, Sync and click on "Open Command Prompt" (see the image) below.

Visual Studio

Once in the Cmd prompt, go ahead with the following two instructions.

git fetch --all

Then you do

git reset --hard origin/master

This will overwrite the existing local version with the one on the Git server.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shiraz
  • 188
  • 3
  • 10
13

I wrote about this ages ago after having these same problems myself:

How to delete/revert a Git commit

Basically you just need to do:

git log, get the first seven characters of the SHA hash, and then do a git revert <sha> followed by git push --force.

You can also revert this by using the Git revert command as follows: git revert <sha> -m -1 and then git push.

AO_
  • 2,573
  • 3
  • 30
  • 31
12

Try this, hard reset to previous commit where those files were not added, then:

git reset --hard <commit_hash>

Make sure you have a backup of your changes just in case, as it's a hard reset, which means they'll be lost (unless you stashed earlier)

sed
  • 5,431
  • 2
  • 24
  • 23
12

If you simply want to trash all your local changes/commits and make your local branch look like the origin branch you started from...

git reset --hard origin/branch-name
Zoe
  • 27,060
  • 21
  • 118
  • 148
JeremyWeir
  • 24,118
  • 10
  • 92
  • 107
11

If you want to undo the very first commit in your repo

You'll encounter this problem:

$ git reset HEAD~
fatal: ambiguous argument 'HEAD~': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

The error occurs because if the last commit is the initial commit (or no parents) of the repository, there is no HEAD~.

Solution

If you want to reset the only commit on "master" branch

$ git update-ref -d HEAD
$ git rm --cached -r .
Nic
  • 12,220
  • 20
  • 77
  • 105
10

Get last commit ID by using this command (in the log one on the top it is the latest one):

git log

Get the commit id (GUID) and run this command:

git revert <commit_id>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
9
#1) $ git commit -m "Something terribly misguided" 
#2) $ git reset HEAD~                              

[ edit files as necessary ]

 #3) $ git add .
#4) $ git commit -c ORIG_HEAD  
Bhojani Asgar
  • 93
  • 1
  • 10
9

If you have made local commits that you don't like, and they have not been pushed yet you can reset things back to a previous good commit. It will be as if the bad commits never happened. Here's how:

In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder for your Git repo. Run git status and make sure you have a clean working tree. Each commit has a unique hash (which looks something like 2f5451f). You need to find the hash for the last good commit (the one you want to revert back to). Here are two places you can see the hash for commits: In the commit history on GitHub or Bitbucket or website. In your terminal (Terminal, Git Bash, or Windows Command Prompt) run the command git log --online Once you know the hash for the last good commit (the one you want to revert back to), run the following command (replacing 2f5451f with your commit's hash):

git reset 2f5451f
git reset --hard 2f5451f

NOTE: If you do git reset the commits will be removed, but the changes will appear as uncommitted, giving you access to the code. This is the safest option because maybe you wanted some of that code and you can now make changes and new commits that are good. Often though you'll want to undo the commits and throw away the code, which is what git reset --hard does.

Abubakar Khalid
  • 109
  • 2
  • 5
8
git revert commit

This will generate the opposite changes from the commit which you want to revert back, and then just commit that changes. I think this is the simplest way.

https://git-scm.com/docs/git-revert

Fabian Lauer
  • 8,891
  • 4
  • 26
  • 35
Georgi Georgiev
  • 362
  • 6
  • 9
8

How to edit an earlier commit

Generally I don't want to undo a bunch of commits, but rather edit an earlier commit to how I wish I had committed it in the first place.

I found myself fixing a past commit frequently enough that I wrote a script for it.

Here's the workflow:

  1. git commit-edit <commit-hash>
    

    This will drop you at the commit you want to edit.

    The changes of the commit will be unstaged, ready to be staged as you wish it was the first time.

  2. Fix and stage the commit as you wish it had been in the first place.

    (You may want to use git stash save --keep-index to squirrel away any files you're not committing)

  3. Redo the commit with --amend, eg:

    git commit --amend
    
  4. Complete the rebase:

    git rebase --continue
    

Call this following git-commit-edit and put it in your $PATH:

#!/bin/bash

# Do an automatic git rebase --interactive, editing the specified commit
# Revert the index and working tree to the point before the commit was staged
# https://stackoverflow.com/a/52324605/5353461

set -euo pipefail

script_name=${0##*/}

warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }

[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"

# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")

# Be able to show what commit we're editing to the user
if git config --get alias.print-commit-1 &>/dev/null; then
  message=$(git print-commit-1 "$commit")
else
  message=$(git log -1 --format='%h %s' "$commit")
fi

if [[ $OSTYPE =~ ^darwin ]]; then
  sed_inplace=(sed -Ei "")
else
  sed_inplace=(sed -Ei)
fi

export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)"  # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty  #  Commit an empty commit so that that cache diffs are un-reversed

echo
echo "Editing commit: $message" >&2
echo
Tom Hale
  • 40,825
  • 36
  • 187
  • 242
8

You can use git revert <commit-id>.

And for getting the commit ID, just use git log.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Videsh Chauhan
  • 371
  • 2
  • 18
8
$ git commit -m 'Initial commit'
$ git add forgotten_file
$ git commit --amend

It’s important to understand that when you’re amending your last commit, you’re not so much fixing it as replacing it entirely with a new, improved commit that pushes the old commit out of the way and puts the new commit in its place. Effectively, it’s as if the previous commit never happened, and it won’t show up in your repository history.

The obvious value to amending commits is to make minor improvements to your last commit, without cluttering your repository history with commit messages of the form, “Oops, forgot to add a file” or “Darn, fixing a typo in last commit”.

2.4 Git Basics - Undoing Things

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
8

I usually first find the commit hash of my recent commit:

git log

It looks like this: commit {long_hash}

Copy this long_hash and reset to it (go back to same files/state it was on that commit):

git reset --hard {insert long_hash without braces}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lbragile
  • 7,549
  • 3
  • 27
  • 64
  • Notice the ``--hard option` will discard all changes not allowing us to discard only some files – Maf Mar 11 '21 at 16:38
8

Visual Studio Code makes this very easy.

VS Code

Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66
  • And this wasn't covered by one of the previous 151 answers (not a rhetorical question)? (Including deleted answers). In any case, you could make an (annotated) list of links to similar answers (as 152 answers (including deleted answer) as 6 long, long pages makes it difficult to navigate) to make navigation easier - say the ones that contain solutions using Visual Studio Code. ([30 synonyms for Visual Studio Code have been observed in the wild](https://pmortensen.eu/EditOverflow/_Wordlist/EditOverflowList_latest.html) so far.) – Peter Mortensen Jun 23 '21 at 22:21
  • No, it was not. – Kyle Delaney Jun 24 '21 at 20:49
8
git reset --soft HEAD~1

Soft: This will remove the commit from local only and keep the changes done in files as it is.

    git reset --hard HEAD~1
    git push origin master

Hard: This will remove that commit from local and remote and remove changes done in files.

vidur punj
  • 5,019
  • 4
  • 46
  • 65
6
git push --delete (branch_name) //this will be removing the public version of your branch

git push origin (branch_name) //This will add the previous version back
omkaartg
  • 2,676
  • 1
  • 10
  • 21
5

git reset HEAD@{n} will reset your last n actions.

For reset, for the last action, use git reset HEAD@{1}.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1583465
  • 167
  • 1
  • 2
  • 11
5

If the repository has been committed locally and not yet pushed to the server, another crude/layman way of solving it would be:

  1. Git clone the repository in another location.
  2. Copy the modifications (files/directories) from the original repository into this new one. Then commit and push with the changes from the new one.
  3. Replace the old repository with this new one.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
copycat
  • 27
  • 1
  • 3
4

If you have committed changes to Git, but have not yet pushed those changes to the remote repository, you can use the git reset command to undo those commits from your local repository.

Here's how:

  1. Use the git log command to find the commit hash of the commit that you want to undo. The commit hash is a long string of numbers and letters that uniquely identifies the commit. You can copy the commit hash to your clipboard by highlighting it and pressing Ctrl + C on Windows or Command + C on macOS.

    git log
    commit 1234567890abcdefg
    Author: Your Name <your.email@example.com>
    Date:   Mon Feb 21 13:42:24 2022 -0500
    
       Commit message goes here
    
  2. Use the git reset command with the --hard option and the commit hash that you want to reset to. This will remove all the commits after the specified commit from your local repository, including any changes made in those commits.

    git reset --hard 1234567890abcdefg
    

    Note that the --hard option will permanently delete any changes that you have made since the specified commit. If you want to keep your changes as unstaged changes in your working directory, you can use the --soft option instead of --hard.

    git reset --soft 1234567890abcdefg
    
  3. After running the git reset command, you can use the git log command again to verify that the unwanted commits have been removed from your local repository.

    $ git log
    commit 1234567890abcdefg
    Author: Your Name <your.email@example.com>
    Date:   Mon Feb 21 13:42:24 2022 -0500
    
        Commit message goes here
    

If the unwanted commits are no longer in the log, you have successfully removed them from your local repository.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tharindu Lakshan
  • 3,995
  • 6
  • 24
  • 44
3

You can use the git reset unwanted_file command with the file you don't want to stage. By using this command, we can move the changed file from the staging area to the working directory.

How can I undo commits in Git locally and remotely?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

In case if you want to revert to a last commit and remove the log history as well

Use the below command. Let’s say you want to go to a previous commit which has commit ID SHA-1 hash value:

71e2e57458bde883a37b332035f784c6653ec509

Then you can point to this commit. It will not display any log message after this commit and all history will be erased after that.

git push origin +71e2e57458bde883a37b332035f784c6653ec509^:master

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ManojP
  • 6,113
  • 2
  • 37
  • 49
2

In Visual Studio, simply revert your commit then push it together with the auto created revert commit. Everything is shown in the screen shots below

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Siraf
  • 1,133
  • 9
  • 24
  • I use VSCode a lot. Nice answer! – Abs Mar 23 '23 at 19:04
  • @Abs: How can you say that? This answer is clearly for [Visual Studio](https://en.wikipedia.org/wiki/Visual_Studio), not [Visual Studio Code](https://en.wikipedia.org/wiki/Visual_Studio_Code). They are two different things (thanks, Microsoft marketing). – Peter Mortensen Mar 30 '23 at 11:36
1

the best way for this siatuation use git reset, depend on your purpose of you to choose one of these option below. To remember action, I recommend the order:

  1. git reset --soft HEAD^:
    uncommit changes, changes are left in staging/index/cached
  2. git reset --mixed HEAD^: (default):
    uncommit changes + unstage, changes are left in working tree
  3. git reset --hard HEAD^:
    uncommit changes + unstage + remove changes, nothing left.
Manh Do
  • 111
  • 8
-2

You can use github desktop. After adding a commit it shows a popup to undo a commit. It is very easy to undo a latest commit from it