Git вернуть удаленный файл
В любой момент вам может потребоваться что-либо отменить. Здесь мы рассмотрим несколько основных способов отмены сделанных изменений. Будьте осторожны, не все операции отмены в свою очередь можно отменить! Это одна из редких областей Git, где неверными действиями можно необратимо удалить результаты своей работы.
Отмена может потребоваться, если вы сделали коммит слишком рано, например, забыв добавить какие-то файлы или комментарий к коммиту. Если вы хотите переделать коммит — внесите необходимые изменения, добавьте их в индекс и сделайте коммит ещё раз, указав параметр --amend :
Например, если вы сделали коммит и поняли, что забыли проиндексировать изменения в файле, который хотели добавить в коммит, то можно сделать следующее:
В итоге получится единый коммит — второй коммит заменит результаты первого.
Очень важно понимать, что когда вы вносите правки в последний коммит, вы не столько исправляете его, сколько заменяете новым, который полностью его перезаписывает. В результате всё выглядит так, будто первоначальный коммит никогда не существовал, а так же он больше не появится в истории вашего репозитория.
Not the answer you're looking for? Browse other questions tagged git or ask your own question.
Linked
Related
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.5.11.42086
Restore specified paths in the working tree with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source.
The command can also be used to restore the content in the index with --staged , or restore both the working tree and the index with --staged --worktree .
By default, if --staged is given, the contents are restored from HEAD , otherwise from the index. Use --source to restore from a different commit.
See "Reset, restore and revert" in git[1] for the differences between the three commands.
THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
Отмена действий с помощью git restore
Git версии 2.23.0 представил новую команду: git restore . По сути, это альтернатива git reset, которую мы только что рассмотрели. Начиная с версии 2.23.0, Git будет использовать git restore вместо git reset для многих операций отмены.
Давайте проследим наши шаги и отменим действия с помощью git restore вместо git reset .
Отмена индексации файла с помощью git restore
В следующих двух разделах показано, как работать с индексом и изменениями рабочей копии с помощью git restore . Приятно то, что команда, которую вы используете для определения состояния этих двух областей, также напоминает вам, как отменить изменения в них. Например, предположим, что вы изменили два файла и хотите зафиксировать их как два отдельных изменения, но случайно набираете git add * и индексируете их оба. Как вы можете убрать из индекса один из двух? Команда git status напоминает вам:
Прямо под текстом «Changes to be committed», написано использовать git restore --staged … для отмены индексации файла. Итак, давайте воспользуемся этим советом, чтобы убрать из индекса файл CONTRIBUTING.md :
Файл CONTRIBUTING.md изменен, но снова не индексирован.
Откат измененного файла с помощью git restore
Что, если вы поймете, что не хотите сохранять изменения в файле CONTRIBUTING.md ? Как легко его откатить — вернуть обратно к тому, как он выглядел при последнем коммите (или изначально клонирован, или каким-либо образом помещён в рабочий каталог)? К счастью, git status тоже говорит, как это сделать. В выводе последнего примера, неиндексированная область выглядит следующим образом:
Он довольно недвусмысленно говорит, как отменить сделанные вами изменения. Давайте сделаем то, что написано:
Важно понимать, что git restore — опасная команда. Любые локальные изменения, внесенные в этот файл, исчезнут — Git просто заменит файл последней зафиксированной версией. Никогда не используйте эту команду, если точно не знаете, нужны ли вам эти несохраненные локальные изменения.
Но вся штука в том, что для исправления проблемы нужно знать точное название команды. И здесь у нас возникает типичная проблема курицы и яйца. В этой статье рассказывается о командах, которые помогают решить проблемные ситуации.
Черт, я сделал что-то не то. Дайте мне волшебную машину времени!
Эта команда позволяет восстановить случайно удаленные данные, откатив слияние, после которого случилась неприятность. 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 адресуйте ему.
Если вам нужно обнулить изменения и полностью откатиться до исходной версии, то можно попробовать сделать именно так. Но помните — эти команды разрушительны и необратимы.
Внимание! Эта статья не является исчерпывающим руководством. И да, есть и другие способы сделать то же самое, причем еще лучше. Но я пришел именно к этим вариантам методом проб и ошибок. Потом у меня появилась сумасшедшая идея поделиться находками. Берите это или уходите!
Комментарий эксперта
Даниил Пилипенко, директор центра подбора IT-специалистов SymbioWay и евангелист бэкенд-направления онлайн-университета Skillbox, дополнил перевод мнением о Git и его актуальности для разработчиков.
Если вы начинающий разработчик и собираетесь устраиваться на работу, обязательно изучите Git! Вы должны знать, что такое система контроля версий и зачем она нужна, что такое коммит, ветка, как клонировать репозиторий и отправлять сделанные изменения на сервер, как получать новые изменения с сервера, как делать merge, какие бывают виды “reset”. Поначалу эта тема вам может показаться непонятной и сложной, но вам нужно лишь привыкнуть пользоваться Git, и отвыкнуть вы уже не сможете.
Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I find I need to restore that file.
I know I can checkout a file using git checkout HEAD^ foo.bar , but I don't really know when that file was deleted.
- What would be the quickest way to find the commit that deleted a given filename?
- What would be the easiest way to get that file back into my working copy?
I'm hoping I don't have to manually browse my logs, checkout the entire project for a given SHA and then manually copy that file into my original project checkout.
note that the previous comment answers the question in the title, not in the body -- that includes finding out when the file was deleted.
@hhh git checkout deletedFile will undelete deletedFile if it's been deleted but that deletion has not yet been staged or committed. That's not what the question here is asking for; this question is about how to restore a file whose deletion was committed many commits ago.
Отмена индексации файла
Следующие два раздела демонстрируют как работать с индексом и изменениями в рабочем каталоге. Радует, что команда, которой вы определяете состояние этих областей, также подсказывает вам как отменять изменения в них. Например, вы изменили два файла и хотите добавить их в разные коммиты, но случайно выполнили команду git add * и добавили в индекс оба. Как исключить из индекса один из них? Команда git status напомнит вам:
Прямо под текстом «Changes to be committed» говорится: используйте git reset HEAD … для исключения из индекса. Давайте последуем этому совету и отменим индексирование файла CONTRIBUTING.md :
Команда выглядит несколько странно, но — работает! Файл CONTRIBUTING.md изменен, но больше не добавлен в индекс.
Команда git reset может быть опасной если вызвать её с параметром --hard . В приведенном примере файл не был затронут, следовательно команда относительно безопасна.
На текущий момент этот магический вызов — всё, что вам нужно знать о команде git reset . Мы рассмотрим в деталях что именно делает reset и как с её помощью делать действительно интересные вещи в разделе Раскрытие тайн reset главы 7.
If you want to restore all of the files at once
Remember to use the period because it tells git to grab all of the files.
This command will reset the head and unstage all of the changes:
Then run this to restore all of the files:
Then doing a git status, you'll get:
This is kinda the simplest solution and works for bunch of files (lets say you have deleted multiple files / folders). good job dude+
Use git ls-files to checkout deleted(-d) or modified(-m) files.
Do you can want see this
that goes for cases where you used
before you commit something.
You may also want to get rid of created files that have not yet been created. And you do not want them. With :
You did not report fully the answer you copied. In fact git checkout -- . does not help to recover deleted files and is equivalent to what the asker tried: git checkout . . The part which can work is the one you didn't copy: git checkout
If you have not committed any changes all you have to do is stash those changes and you will be back to the last working commit.
Thisc is nice solution because you can remove it from stash. If is a hack or not, it's matter of taste. Whole idea of stash is clever hack.
Found this post while looking for answers on how to un-delete a file that was deleted in my working directory after a merge from another's branch. No commit was yet made after the merge. Since it was a merge in progress, i could not just add it back using:
I had to do another step in addition to the reset to bring the file back:
This was the easiest way for me:
Another way that also worked for me:
if you are looking for a deleted directory.
Newer git (mine is 2.27.0) is more friendly and the actual commands are shown during "git status". For example, if you deleted the file tf.c, then
You would use "git restore tf.c" to get it back, as it saz. No more search!
For example git checkout 5a6b3179e58edff9c90326b9a04284b02fd67bd0 "src-ui/views/includes/radar.pug"
(executed in the branch that we want the file to go into)
After that command executes, the restored file will exist in the original location (which will need to be comited)
and / or simply a git checkout master path/to/the/file.bin so that you just undelete that file without loosing any other change you might have done. PS: this should be the accepted answer.
1.Find that particular commit to which you want to revert using:
2.Revert to that commit using :
Now you local branch would have all files in particular
If you have installed ToroiseGIT then just select "Revert. " menu item for parent folder popup-menu.
CAUTION: commit any work you wish to retain first.
You may reset your workspace (and recover the deleted files)
@JeanPaul maybe I'm misunderstanding but it put my workspace in the original state (deleted file now present).
@Marc It could work but only if there is no visible file in the directory, because otherwise ./* will be expanded by bash to match those files before being sent to git.
I happened to move (instead of copy) some json files from one folder to another within the same repository. Then I renamed those files and changed some contents in the new location. However I quickly learned that I have not copied and totally deleted the files from previous location.
Did this for all the files and they are back.
You can also include multiple files separated by space.
Easy fix, btw this will not change / delete the new files.
I had the same problem however none of the above solutions worked for me. What I ended up doing was:
- create an empty file with the same name
- compare this file with its local history
- copy history across to empty file.
I had the same problem and none of the answers here I tried worked for me either. I am using Intellij and I had checked out a new branch git checkout -b minimalExample to create a "minimal example" on the new branch of some issue by deleting a bunch of files and modifying a bunch of others in the project. Unfortunately, even though I didn't commit any of the changes on the new "minimal example" branch, when I checked out my "original" branch again all of the changes and deletions from the "minimal example" branch had happened in the "original" branch too (or so it appeared). According to git status the deleted files were just gone from both branches.
Fortunately, even though Intellij had warned me "deleting these files may not be fully recoverable", I was able to restore them (on the minimal example branch from which they had actually been deleted) by right-clicking on the project and selecting Local History > Show History (and then Restore on the most recent history item I wanted). After Intellij restored the files in the "minimal example" branch, I pushed the branch to origin. Then I switched back to my "original" local branch and ran git pull origin minimalExample to get them back in the "original" branch too.
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
OPTIONS
Restore the working tree files with the content from the given tree. It is common to specify the source tree by naming a commit, branch or tag associated with it.
If not specified, the contents are restored from HEAD if --staged is given, otherwise from the index.
As a special case, you may use "A. B" as a shortcut for the merge base of A and B if there is exactly one merge base. You can leave out at most one of A and B , in which case it defaults to HEAD .
Interactively select hunks in the difference between the restore source and the restore location. See the “Interactive Mode” section of git-add[1] to learn how to operate the --patch mode.
Note that --patch can accept no pathspec and will prompt to restore all modified paths.
Specify the restore location. If neither option is specified, by default the working tree is restored. Specifying --staged will only restore the index. Specifying both restores both.
Quiet, suppress feedback messages. Implies --no-progress .
Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified. This flag enables progress reporting even if not attached to a terminal, regardless of --quiet .
Note that during git rebase and git pull --rebase , ours and theirs may appear swapped. See the explanation of the same options in git-checkout[1] for details.
When restoring files on the working tree from the index, recreate the conflicted merge in the unmerged paths.
The same as --merge option above, but changes the way the conflicting hunks are presented, overriding the merge.conflictStyle configuration variable. Possible values are "merge" (default), "diff3", and "zdiff3".
When restoring files on the working tree from the index, do not abort the operation if there are unmerged entries and neither --ours , --theirs , --merge or --conflict is specified. Unmerged paths on the working tree are left alone.
In sparse checkout mode, by default is to only update entries matched by and sparse patterns in $GIT_DIR/info/sparse-checkout. This option ignores the sparse patterns and unconditionally restores any files in .
If names an active submodule and the restore location includes the working tree, the submodule will only be updated if this option is given, in which case its working tree will be restored to the commit recorded in the superproject, and any local modifications overwritten. If nothing (or --no-recurse-submodules ) is used, submodules working trees will not be updated. Just like git-checkout[1], this will detach HEAD of the submodule.
In overlay mode, the command never removes files when restoring. In no-overlay mode, tracked files that do not appear in the --source tree are removed, to make them match exactly. The default is no-overlay mode.
Pathspec is passed in instead of commandline args. If is exactly - then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config[1]). See also --pathspec-file-nul and global --literal-pathspecs .
Only meaningful with --pathspec-from-file . Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
Do not interpret any more arguments as options.
Limits the paths affected by the operation.
For more details, see the pathspec entry in gitglossary[7].
EXAMPLES
The following sequence switches to the master branch, reverts the Makefile to two revisions back, deletes hello.c by mistake, and gets it back from the index.
take a file out of another commit
restore hello.c from the index
If you want to restore all C source files to match the version in the index, you can say
Note the quotes around *.c . The file hello.c will also be restored, even though it is no longer in the working tree, because the file globbing is used to match entries in the index (not in the working tree by the shell).
To restore all files in the current directory
or to restore all working tree files with top pathspec magic (see gitglossary[7])
To restore a file in the index to match the version in HEAD (this is the same as using git-reset[1])
or you can restore both the index and the working tree (this the same as using git-checkout[1])
Отмена индексации файла
Следующие два раздела демонстрируют как работать с индексом и изменениями в рабочем каталоге. Радует, что команда, которой вы определяете состояние этих областей, также подсказывает вам как отменять изменения в них. Например, вы изменили два файла и хотите добавить их в разные коммиты, но случайно выполнили команду git add * и добавили в индекс оба. Как исключить из индекса один из них? Команда git status напомнит вам:
Прямо под текстом «Changes to be committed» говорится: используйте git reset HEAD … для исключения из индекса. Давайте последуем этому совету и отменим индексирование файла CONTRIBUTING.md :
Команда выглядит несколько странно, но — работает! Файл CONTRIBUTING.md изменен, но больше не добавлен в индекс.
Команда git reset может быть опасной если вызвать её с параметром --hard . В приведенном примере файл не был затронут, следовательно команда относительно безопасна.
На текущий момент этот магический вызов — всё, что вам нужно знать о команде git reset . Мы рассмотрим в деталях что именно делает reset и как с её помощью делать действительно интересные вещи в разделе Раскрытие тайн reset главы 7.
Отмена изменений в файле
Что делать, если вы поняли, что не хотите сохранять свои изменения файла CONTRIBUTING.md ? Как можно просто отменить изменения в нём — вернуть к тому состоянию, которое было в последнем коммите (или к начальному после клонирования, или еще как-то полученному)? Нам повезло, что git status подсказывает и это тоже.
В выводе команды из последнего примера список изменений выглядит примерно так:
Здесь явно сказано как отменить существующие изменения. Давайте так и сделаем:
Как видите, откат изменений выполнен.
Важно понимать, что git checkout -- — опасная команда. Все локальные изменения в файле пропадут — Git просто заменит его версией из последнего коммита. Ни в коем случае не используйте эту команду, если вы не уверены, что изменения в файле вам не нужны.
Если вы хотите сохранить изменения в файле, но прямо сейчас их нужно отменить, то есть способы получше, такие как ветвление и припрятывание — мы рассмотрим их в главе Ветвление в Git.
Помните, все что попало в коммит почти всегда Git может восстановить. Можно восстановить даже коммиты из веток, которые были удалены, или коммиты, перезаписанные параметром --amend (см. Восстановление данных). Но всё, что не было включено в коммит и потеряно — скорее всего, потеряно навсегда.
30 Answers 30
Find the last commit that affected the given path. As the file isn't in the HEAD commit, that previous commit must have deleted it.
Then checkout the version at the commit before, using the caret ( ^ ) symbol:
Or in one command, if $file is the file in question.
If you are using zsh and have the EXTENDED_GLOB option enabled, the caret symbol won't work. You can use ~1 instead.
For some reason, this won't work in zsh. ± git checkout $(git rev-list -n 1 HEAD "spec/Sporkfile_example.rb")^ -- "spec/Sporkfile_example.rb" zsh: no matches found: b71c152d8f38dcd23ad7600a93f261a7252c59e9^ I switched to bash & it worked fine though.
From the windows command line I got an error. error: pathspec
@zoras zsh has it's own expansion on '^' I believe, but you can use the alternative syntax of '~1': git checkout
On windows cmd prompt, the ^ character is the escape character! Therefore, on cmd, you have to type ^^ to tell cmd you want a single literal ^ and that your not escaping something else after it. What's happening to many people is that the ^ is followed by a space. So cmd thinks you're escaping the space -- which yields simply a space character. Thus, by the time git gets the cli arguments, it sees SHA1 and not SHA1^ . It's really annoying. ~ isn't an escape character, so that's why that still works. (PS. if you think googlers will want this info, please upvote this comment)
- Use git log --diff-filter=D --summary to get all the commits which have deleted files and the files deleted;
- Use git checkout $commit~1 path/to/file.ext to restore the deleted file.
Where $commit is the value of the commit you've found at step 1, e.g. e4cf499627
this is by far the easiest and intuitive approach. git log -- *PartOfMyFileName* . Thanks for the $commit~1
the git checkout $commit~1 filename syntax works perfect for individual files, and also works for whole directories. ie: to restore all deleted images in ./images from sha 12345: git checkout 12345~1 images . thanks for this answer!
@Alexar $commit~1 means you should add the name of the commit. Something like 1d0c9ef6eb4e39488490543570c31c2ff594426c where $commit is.
To restore all those deleted files in a folder, enter the following command.
This is probably the easiest method. Its perverted how difficult git has made even the simplest task.
The ls-files sub-command is handy, but doesn't seem to work for files that had been removed with git rm i.e. staged, let alone committed, which is what the OP asked.
@RomainValeri - It is 2019. The tools work for me. I do not work for the tools. If learing is required then the design is broken.
@RomainValeri , @jww you're both right. git is nearly unparalleled in its usefulness, while also imfamously complicated to learn. An appreciable proportion of git s learning curve is due to an inconsistent / unintuitive UI. Personally, when I'm learning something difficult, one of the things that gives me reassurance is seeing that other (competent) people also struggled to figure it out
I came to this question looking to restore a file I just deleted but I hadn't yet committed the change. Just in case you find yourself in this situation, all you need to do is the following:
git checkout HEAD -- path/to/file.ext
If you’re insane, use git-bisect . Here's what to do:
Now it's time to run the automated test. The shell command '[ -e foo.bar ]' will return 0 if foo.bar exists, and 1 otherwise. The "run" command of git-bisect will use binary search to automatically find the first commit where the test fails. It starts halfway through the range given (from good to bad) and cuts it in half based on the result of the specified test.
Now you're at the commit which deleted it. From here, you can jump back to the future and use git-revert to undo the change,
or you could go back one commit and manually inspect the damage:
You can also use good and bad manually, if it's something that can't be checked automatically. See the bisect man page.
@avdgaag the git bisect run tells Git to automate bisection by running the command following word 'run' where the command must return 0 for a good version (see git help bisect for details). The '[ -e foo.bar ]' is a standard expression for testing if file foo.bar does exists (the implementation is usually in file /usr/bin/[ which is usually hardlinked to /usr/bin/test ) and the single quation marks are used to put that all as a single command line argument.
Great idea. I tried this approach and it identified a commit prior to deletion, but not the commit that actually deleted the file. And in another test it identified 2 commits prior to the deletion.
Insane? Maybe. But bisect is a great way to help find where a bug was introduced and so it's a valuable skill to learn anyway. So although maybe not the 'correct' or most 'correct' way here it's still a good idea and worth a +1 definitely!
My new favorite alias, based on bonyiii's answer (upvoted), and my own answer about "Pass an argument to a Git alias command":
I have lost a file, deleted by mistake a few commits ago?
Quick:
Warning, with Git 2.23 (Q3 2019) comes the experimental command named git restore (!).
So rename this alias (as shown below).
Robert Dailey proposes in the comments the following alias:
For setting the alias from the command line, I used this command:
Here is my alias, works wonderfully: restore-file = !git checkout $(git rev-list -n 1 HEAD -- "$1")^ -- "$1"
For setting the alias from the command line, I used this command: git config --global alias.restore "\!git checkout \$(git rev-list -n 1 HEAD -- \"\$1\")^ -- \"\$1\""
If you know the filename, this is an easy way with basic commands:
List all the commits for that file.
The last commit (topmost) is the one that deleted the file. So you need to restore the second to last commit.
This is the first solution I've seen that's simple enough that I won't have to come back here to find it next time. Maybe.
To restore a deleted and commited file:
It was tested on Git version 1.7.5.4.
That didn't work for me. After the checkout, I got error: pathspec 'foo' did not match any file(s) known to git. I made sure that the filename was correct. Git version 2.7.0
-1; this is wrong. These commands will undo a deletion that hasn't yet been committed (the first one unstages the deletion, if it's staged, and the second one discards unstaged changes to the file), but you're claiming here that they'll restore a committed deletion of the file, which simply isn't true and will fail with an error like that in @wisbucky's comment above.
@MarkAmery Indeed, I think this command worked well for those developers, who didn't made explicit staging for committing for removed files with git add -A , but so the restored file was still in non committed stage.
Get the id of the commit where the file was deleted using one of the ways below.
You should get something like:
commit bfe68bd117e1091c96d2976c99b3bcc8310bebe7 Author: Alexander Orlov Date: Thu May 12 23:44:27 2011 +0200
commit 3ea4e3af253ac6fd1691ff6bb89c964f54802302 Author: Alexander Orlov Date: Thu May 12 22:10:22 2011 +0200
3. Now using the commit id bfe68bd117e1091c96d2976c99b3bcc8310bebe7 do:
As the commit id references the commit where the file was already deleted you need to reference the commit just before bfe68b which you can do by appending ^1 . This means: give me the commit just before bfe68b.
This is the same approach as the accepted answer, but with some more ways to find the deleting commit. I still like the approach taken in the accepted answer, but these are good alternatives. Thanks!
I assume that first checking out the deleted file and then (without changing it) commiting it does not create a copy of the file. Right? (I need to do this with images, and a copies would make the repository bigger)
If you only made changes and deleted a file, but not commit it, and now you broke up with your changes
but your deleted files did not return, you simply do the following command:
And presto, your file is back.
Actually, this question is directly about Git, but somebody like me works with GUI tools like the WebStorm VCS other than knowing about Git CLI commands.
I right click on the path that contains the deleted file, and then go to Git and then click on Show History.
The VCS tools show all revisions train and I can see all commits and changes of each of them.
Then I select the commits that my friend delete the PostAd.js file. now see below:
And now, I can see my desire deleted file. I just double-click on the filename and it recovers.
I know my answer is not Git commands, but it is fast, reliable and easy for beginner and professional developers. WebStorm VCS tools are awesome and perfect for working with Git and it doesn't need any other plugin or tools.
Why doesn't git checkout . reset the workspace to HEAD ?
24 Answers 24
The output tells you what you need to do. git reset HEAD cc.properties etc.
This will unstage the rm operation. After that, running a git status again will tell you that you need to do a git checkout -- cc.properties to get the file back.
Update: I have this in my config file
which I usually use to unstage stuff.
How do you do this for multiple deleted files? Running git reset HEAD <> multiple times would be cumbersome, any efficient way to get it done?
@zyy The -- is to indicate files. e.g. If you have a branch called foo . git co foo will checkout to the branch. However, git co -- foo will checkout the file named foo .
You've staged the deletion so you need to do:
git checkout . only checks out from the index where the deletion has already been staged.
Just do git checkout path/to/file-I-want-to-bring-back.txt
Didn't work for me, git said it doesn't know any file by that name, although the file is tracked. I didn't commit either, I only deleted a file using netbeans' context menu mistakenly.
To recover all unstaged deletions at once, automatically, without specifying each single path:
To recover all staged deletions at once, automatically, without specifying each single path:
I accidentally deleted over 500 files and this worked a treat because it also kept all of my valid changes (the first line is what I used). Thanks.
Accidentally deleted all contents of a repo right after a successful build. The first command saved my bacon.
Before this would work for me, I had to run git status --long | grep 'deleted:' | awk '
Very useful, wanted to keep untracked files but get rid of deleted and modified, just changed -d to -m for handling the modified.
Note this doesn't work if you have spaces in your file names/paths. I think git ls-files -d | sed -e "s/\(.*\)/'\1'/" | xargs git checkout -- will work.
Since you're doing a git checkout . , it looks like you are trying to restore your branch back to the last commit state.
You can achieve this with a git reset HEAD --hard
Doing this may remove all your latest modifications and unstage your modifications, e.g., you can lose work. It may be what you want, but check out the docs to make sure.
Woww!! Careful with this. You might be right, but someone could be confused and blow up their whole code. It'd be cool if you add a bigger warning.
This is exactly what I needed. Doesn't blow up your whole code - simply brings you back to your most recent commit.
I ended up with hundreds of missing files at one point. This is the only practical way to fix the problem. Thanks!
to delete a file then
doesn't work, so in that case
I like this answer. There is no doubt that you are affecting only the specific file you removed. 1) git checkout path/to/filename 2) git checkout -- path/to/filename
If you haven't commited the file, git checkout HEAD path/to/filename might be sufficient. So checkout from last, not previous commit.
Here is the command that helped me on my mac. I tried a few of the other solutions but they did not work for me.
Git version on OSX Mavericks
Command
Here are different cases as a reference to help others:
If the deletion has not been committed, the command below will restore the deleted file in the working tree.
You can get a list of all the deleted files in the working tree using the command below.
If the deletion has been committed, find the commit where it happened, then recover the file from this commit.
It should give you something like c46e81aa403ecb8a0f7a323a358068345 , now use this commit hash with the parent operator ( ^ ) like so:
In case you are looking for the path of the file to recover, the following command will display a summary of all deleted files.
If you want to just display the list of files:
Читайте также: