Как отменить hard reset git

Обновлено: 04.07.2024

1,462 1 1 gold badge 7 7 silver badges 21 21 bronze badges 51.8k 45 45 gold badges 151 151 silver badges 260 260 bronze badges If anyone is looking for how to undo a hard reset, check in Undoing a git reset --hard HEAD

1. The solutions are very similar.

4 Answers 4

Short answer:

Long answer:

Git keeps a log of all ref updates (e.g., checkout, reset, commit, merge). You can view it by typing:

Somewhere in this list is the commit that you lost. Let's say you just typed git reset HEAD

and want to undo it. My reflog looks like this:

The first line says that HEAD 0 positions ago (in other words, the current position) is 3f6db14; it was obtained by resetting to HEAD

. The second line says that HEAD 1 position ago (in other words, the state before the reset) is d27924e. It was obtained by checking out a particular commit (though that's not important right now). So, to undo the reset, run git reset HEAD@ (or git reset d27924e ).

If, on the other hand, you've run some other commands since then that update HEAD, the commit you want won't be at the top of the list, and you'll need to search through the reflog .

One final note: It may be easier to look at the reflog for the specific branch you want to un-reset, say master, rather than HEAD :

I staged my changes with git add , but never committed. Now my changes are gone!

This is a bit trickier to recover from. git does have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using git fsck .

Вроде бы нашел решение, помогла команда git reset --hard HEAD@

живи долго и счастливо, ты мой ангел и ты меня спас от грубейшей ошибки в ночь на дедлайн

Да, команда git reset --hard HEAD@ <1>откатывает последнее действие. Если захотите относительно коммитов, то можете использовать ещё:
git reset --hard HEAD

Если относительно времени, то так можно:
git reset --hard HEAD@
или
git reset --hard HEAD@

Git, я хочу все отменить! Команды исправления допущенных ошибок

image

Но вся штука в том, что для исправления проблемы нужно знать точное название команды. И здесь у нас возникает типичная проблема курицы и яйца. В этой статье рассказывается о командах, которые помогают решить проблемные ситуации.

Черт, я сделал что-то не то. Дайте мне волшебную машину времени!


image

Эта команда позволяет восстановить случайно удаленные данные, откатив слияние, после которого случилась неприятность. refLog используется ну очень часто — давайте скажем спасибо тому, что предложил добавить эту команду.

Я случайно закоммитил в мастер, хотя это должен был в новую ветку!


Если вы уже закоммитили в публичную ветку, команды не сработают. В этом случае поможет git reset HEAD@ вместо HEAD

Ну вот, я ошибочно закоммитил не в ту ветку


Есть еще один способ, который использует большое количество разработчиков — это cherry-pick.


Мне нужно запустить diff, но ничего не получается

Если вы уверены в том, что изменения были внесены, но diff пустой, вполне может быть, что вы индексировали изменения через add. Поэтому стоит использовать специальный флаг.

git diff --staged

В общем, это не баг, а фича, но она чертовски неочевидная ¯\_(ツ)_/¯

Мне срочно нужно отменить коммит, который сделан 5 коммитов назад


К счастью, не нужно отказываться назад на 5 коммитов, занимаясь копипастом старых и новых файлов. Отменить все это можно при помощи revert.

Кроме того, откатить можно не только коммит, но и целый файл. Правда, это уже будут другие команды…

Отменить изменения в файле

А вот и они, эти другие команды.


Когда я впервые нашел эту возможность, это было КРУТО, КРУТО, К-Р-У-Т-О. Но если задуматься — почему именно checkout — лучший вариант для отмены изменений в файле? :shakes-fist-at-linus-torvalds:

Все, я сдаюсь


Спасибо Eric V. За этот способ. И все жалобы по поводу использования sudo адресуйте ему.

Если вам нужно обнулить изменения и полностью откатиться до исходной версии, то можно попробовать сделать именно так. Но помните — эти команды разрушительны и необратимы.


Внимание! Эта статья не является исчерпывающим руководством. И да, есть и другие способы сделать то же самое, причем еще лучше. Но я пришел именно к этим вариантам методом проб и ошибок. Потом у меня появилась сумасшедшая идея поделиться находками. Берите это или уходите!

image

Комментарий эксперта

Даниил Пилипенко, директор центра подбора IT-специалистов SymbioWay и евангелист бэкенд-направления онлайн-университета Skillbox, дополнил перевод мнением о Git и его актуальности для разработчиков.

Если вы начинающий разработчик и собираетесь устраиваться на работу, обязательно изучите Git! Вы должны знать, что такое система контроля версий и зачем она нужна, что такое коммит, ветка, как клонировать репозиторий и отправлять сделанные изменения на сервер, как получать новые изменения с сервера, как делать merge, какие бывают виды “reset”. Поначалу эта тема вам может показаться непонятной и сложной, но вам нужно лишь привыкнуть пользоваться Git, и отвыкнуть вы уже не сможете.

19 Answers 19

Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs.

You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.

357k 160 160 gold badges 892 892 silver badges 1545 1545 bronze badges 24k 2 2 gold badges 22 22 silver badges 17 17 bronze badges You can use "git reset --hard HEAD@<1>", no need for using SHA1. In most cases it should be enough to use "git reset --hard ORIG_HEAD". git log -g can be a little bit nicer way to view the reflog than git reflog . ^ Just so you know you can stash your local changes before doing a reset --hard, and then just pop them and you lose nothing! Gotta love git. I prefer git reflog over git log -g simply because you get all the information on one line with sha1, HEAD info and commit messages all lined up. Much easier to read.

What you want to do is to specify the sha1 of the commit you want to restore to. You can get the sha1 by examining the reflog ( git reflog ) and then doing

But don't wait too long. after a few weeks git will eventually see that commit as unreferenced and delete all the blobs.

81.3k 41 41 gold badges 170 170 silver badges 231 231 bronze badges 191k 29 29 gold badges 87 87 silver badges 92 92 bronze badges

The answer is hidden in the detailed response above, you can simply do:

(See the output of git reflog show)

3,122 2 2 gold badges 14 14 silver badges 7 7 bronze badges Accidentally reset my repository, thought my work was lost forever. This answer saved my day.

It is possible to recover it if Git hasn't garbage collected yet.

Get an overview of dangling commits with fsck :

Recover the dangling commit with rebase:

15.5k 13 13 gold badges 38 38 silver badges 29 29 bronze badges

as far as i know, --hard will discards uncommitted changes. Since these aren't tracked by git. but you can undo the discarded commit .

where 4bac331 is the discarded commit .

Now just move the head to that commit::


15.9k 8 8 gold badges 85 85 silver badges 93 93 bronze badges

If you're really lucky, like I was, you can go back into your text editor and hit 'undo'.

I know that's not really a proper answer, but it saved me half a day's work so hopefully it'll do the same for someone else!

37.6k 43 43 gold badges 180 180 silver badges 229 229 bronze badges This is actually a very good tip, saved me a lot of times ;) And its way simpler than doing anything in git. and thank you of all goodness gracious in this entire world. thank you. thank you. thank you. This is the only way to recover unstaged changes in files after the hard reset. Saved me too ;) As an additional hint, some IDEs as eclipse also have the recent file history saved. That way, you might even be able to recover older changes after the editor was closed. That worked wonders for me.

How can I undo git reset --hard HEAD

Is it possible to undo the changes caused by the following command? If so, how?


49.7k 24 24 gold badges 153 153 silver badges 160 160 bronze badges 57.1k 54 54 gold badges 117 117 silver badges 144 144 bronze badges This is a great article to assist you with recovering your files.

All my changes were committed, but now the commits are gone!

This situation usually occurs when you run git reset with an argument, as in git reset --hard HEAD

. Don't worry, this is easy to recover from!

If you just ran git reset and haven't done anything else since, you can get back to where you were with this one-liner:

This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).

If, however, you have made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run git reflog <branchname> to see a list of all recent changes made to your branch (including resets). That list will look something like this:

Find the operation in this list that you want to "undo". In the example above, it would be the first line, the one that says "reset: moving to HEAD

". Then copy the representation of the commit before (below) that operation. In our case, that would be master@ (or 3ae5027 , they both represent the same commit), and run git reset --hard <commit> to reset your current branch back to that commit.

In most cases, yes.

Depending on the state your repository was in when you ran the command, the effects of git reset --hard can range from trivial to undo, to basically impossible.

Below I have listed a range of different possible scenarios, and how you might recover from them.

4 Answers 4

Short answer:

Long answer:

Git keeps a log of all ref updates (e.g., checkout, reset, commit, merge). You can view it by typing:

Somewhere in this list is the commit that you lost. Let's say you just typed git reset HEAD

and want to undo it. My reflog looks like this:

The first line says that HEAD 0 positions ago (in other words, the current position) is 3f6db14; it was obtained by resetting to HEAD

. The second line says that HEAD 1 position ago (in other words, the state before the reset) is d27924e. It was obtained by checking out a particular commit (though that's not important right now). So, to undo the reset, run git reset HEAD@ (or git reset d27924e ).

If, on the other hand, you've run some other commands since then that update HEAD, the commit you want won't be at the top of the list, and you'll need to search through the reflog .

One final note: It may be easier to look at the reflog for the specific branch you want to un-reset, say master, rather than HEAD :

I had changes to files in my working directory that I never staged with git add , and never committed. Now my changes are gone!

Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the documentation for git reset :

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

It's possible that you might be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.

Читайте также: