Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

6
  • 8
    Strictly speaking there is a way to recover an already staged file that was replaced with git add. As you mention git add creates an git object for that file that will become a loose object not only when removing the file completely but also when being overwritten with new content. But there is no command to automatically recover it. Instead the file has to be identified and extracted manually or with tools written only for this case (libgit2 will allow this). But this will only pay out if the file is very important and big and could not be rebuild by editing the previous version. Commented Dec 6, 2017 at 13:07
  • 5
    To correct myself: Once the loose object file is found (use meta-data like creation date/time) git cat-file could be used to recover its content. Commented Dec 6, 2017 at 13:22
  • 9
    Another way to recover changes that were staged but not committed and then overwritten by e.g. another git add is via git fsck --unreachable that will list all unreachable obj, which you can then inspect by git show SHA-1_ID or git fsck --lost-found that will >Write dangling objects into .git/lost-found/commit/ or .git/lost-found/other/, depending on type. See also git fsck --help
    – iolsmit
    Commented Apr 27, 2018 at 15:29
  • @iolsmit How can a git add overwrite a change that was staged but not committed? If I created a file a.txt and it had '1' as it's content, how can git add make it have '2' or sth else as it's content? Just looking for an explanation Commented Oct 25, 2022 at 13:17
  • 2
    @FilipSavic If you add the same file multiple times, without committing. E.g. echo 1 > a.txt followed by git add a.txt - do not commit yet - echo 2 > a.txt followed by git add a.txt; now commit e.g. git commit -m "create unreachable blob" and run git fsck --unreachable
    – iolsmit
    Commented Oct 26, 2022 at 18:46